workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6pub mod notifications;
    7pub mod pane;
    8pub mod pane_group;
    9mod path_list;
   10mod persistence;
   11pub mod searchable;
   12mod security_modal;
   13pub mod shared_screen;
   14mod status_bar;
   15pub mod tasks;
   16mod theme_preview;
   17mod toast_layer;
   18mod toolbar;
   19pub mod utility_pane;
   20pub mod welcome;
   21mod workspace_settings;
   22
   23pub use crate::notifications::NotificationFrame;
   24pub use dock::Panel;
   25pub use path_list::PathList;
   26pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   27
   28use anyhow::{Context as _, Result, anyhow};
   29use call::{ActiveCall, call_settings::CallSettings};
   30use client::{
   31    ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
   32    proto::{self, ErrorCode, PanelId, PeerId},
   33};
   34use collections::{HashMap, HashSet, hash_map};
   35use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   36use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   37use futures::{
   38    Future, FutureExt, StreamExt,
   39    channel::{
   40        mpsc::{self, UnboundedReceiver, UnboundedSender},
   41        oneshot,
   42    },
   43    future::{Shared, try_join_all},
   44};
   45use gpui::{
   46    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   47    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   48    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   49    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   50    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   51    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   52};
   53pub use history_manager::*;
   54pub use item::{
   55    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   56    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   57};
   58use itertools::Itertools;
   59use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   60pub use modal_layer::*;
   61use node_runtime::NodeRuntime;
   62use notifications::{
   63    DetachAndPromptErr, Notifications, dismiss_app_notification,
   64    simple_message_notification::MessageNotification,
   65};
   66pub use pane::*;
   67pub use pane_group::{
   68    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   69    SplitDirection,
   70};
   71use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   72pub use persistence::{
   73    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   74    model::{ItemId, SerializedWorkspaceLocation},
   75};
   76use postage::stream::Stream;
   77use project::{
   78    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   79    WorktreeSettings,
   80    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   81    project_settings::ProjectSettings,
   82    toolchain_store::ToolchainStoreEvent,
   83    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   84};
   85use remote::{
   86    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   87    remote_client::ConnectionIdentifier,
   88};
   89use schemars::JsonSchema;
   90use serde::Deserialize;
   91use session::AppSession;
   92use settings::{
   93    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
   94};
   95use shared_screen::SharedScreen;
   96use sqlez::{
   97    bindable::{Bind, Column, StaticColumnCount},
   98    statement::Statement,
   99};
  100use status_bar::StatusBar;
  101pub use status_bar::StatusItemView;
  102use std::{
  103    any::TypeId,
  104    borrow::Cow,
  105    cell::RefCell,
  106    cmp,
  107    collections::{VecDeque, hash_map::DefaultHasher},
  108    env,
  109    hash::{Hash, Hasher},
  110    path::{Path, PathBuf},
  111    process::ExitStatus,
  112    rc::Rc,
  113    sync::{
  114        Arc, LazyLock, Weak,
  115        atomic::{AtomicBool, AtomicUsize},
  116    },
  117    time::Duration,
  118};
  119use task::{DebugScenario, SpawnInTerminal, TaskContext};
  120use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  121pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
  122pub use ui;
  123use ui::{Window, prelude::*};
  124use util::{
  125    ResultExt, TryFutureExt,
  126    paths::{PathStyle, SanitizedPath},
  127    rel_path::RelPath,
  128    serde::default_true,
  129};
  130use uuid::Uuid;
  131pub use workspace_settings::{
  132    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  133    WorkspaceSettings,
  134};
  135use zed_actions::{Spawn, feedback::FileBugReport};
  136
  137use crate::{
  138    item::ItemBufferKind,
  139    notifications::NotificationId,
  140    utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
  141};
  142use crate::{
  143    persistence::{
  144        SerializedAxis,
  145        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  146    },
  147    security_modal::SecurityModal,
  148    utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
  149};
  150
  151pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  152
  153static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  154    env::var("ZED_WINDOW_SIZE")
  155        .ok()
  156        .as_deref()
  157        .and_then(parse_pixel_size_env_var)
  158});
  159
  160static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  161    env::var("ZED_WINDOW_POSITION")
  162        .ok()
  163        .as_deref()
  164        .and_then(parse_pixel_position_env_var)
  165});
  166
  167pub trait TerminalProvider {
  168    fn spawn(
  169        &self,
  170        task: SpawnInTerminal,
  171        window: &mut Window,
  172        cx: &mut App,
  173    ) -> Task<Option<Result<ExitStatus>>>;
  174}
  175
  176pub trait DebuggerProvider {
  177    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  178    fn start_session(
  179        &self,
  180        definition: DebugScenario,
  181        task_context: TaskContext,
  182        active_buffer: Option<Entity<Buffer>>,
  183        worktree_id: Option<WorktreeId>,
  184        window: &mut Window,
  185        cx: &mut App,
  186    );
  187
  188    fn spawn_task_or_modal(
  189        &self,
  190        workspace: &mut Workspace,
  191        action: &Spawn,
  192        window: &mut Window,
  193        cx: &mut Context<Workspace>,
  194    );
  195
  196    fn task_scheduled(&self, cx: &mut App);
  197    fn debug_scenario_scheduled(&self, cx: &mut App);
  198    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  199
  200    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  201}
  202
  203actions!(
  204    workspace,
  205    [
  206        /// Activates the next pane in the workspace.
  207        ActivateNextPane,
  208        /// Activates the previous pane in the workspace.
  209        ActivatePreviousPane,
  210        /// Switches to the next window.
  211        ActivateNextWindow,
  212        /// Switches to the previous window.
  213        ActivatePreviousWindow,
  214        /// Adds a folder to the current project.
  215        AddFolderToProject,
  216        /// Clears all notifications.
  217        ClearAllNotifications,
  218        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  219        ClearNavigationHistory,
  220        /// Closes the active dock.
  221        CloseActiveDock,
  222        /// Closes all docks.
  223        CloseAllDocks,
  224        /// Toggles all docks.
  225        ToggleAllDocks,
  226        /// Closes the current window.
  227        CloseWindow,
  228        /// Opens the feedback dialog.
  229        Feedback,
  230        /// Follows the next collaborator in the session.
  231        FollowNextCollaborator,
  232        /// Moves the focused panel to the next position.
  233        MoveFocusedPanelToNextPosition,
  234        /// Opens a new terminal in the center.
  235        NewCenterTerminal,
  236        /// Creates a new file.
  237        NewFile,
  238        /// Creates a new file in a vertical split.
  239        NewFileSplitVertical,
  240        /// Creates a new file in a horizontal split.
  241        NewFileSplitHorizontal,
  242        /// Opens a new search.
  243        NewSearch,
  244        /// Opens a new terminal.
  245        NewTerminal,
  246        /// Opens a new window.
  247        NewWindow,
  248        /// Opens a file or directory.
  249        Open,
  250        /// Opens multiple files.
  251        OpenFiles,
  252        /// Opens the current location in terminal.
  253        OpenInTerminal,
  254        /// Opens the component preview.
  255        OpenComponentPreview,
  256        /// Reloads the active item.
  257        ReloadActiveItem,
  258        /// Resets the active dock to its default size.
  259        ResetActiveDockSize,
  260        /// Resets all open docks to their default sizes.
  261        ResetOpenDocksSize,
  262        /// Reloads the application
  263        Reload,
  264        /// Saves the current file with a new name.
  265        SaveAs,
  266        /// Saves without formatting.
  267        SaveWithoutFormat,
  268        /// Shuts down all debug adapters.
  269        ShutdownDebugAdapters,
  270        /// Suppresses the current notification.
  271        SuppressNotification,
  272        /// Toggles the bottom dock.
  273        ToggleBottomDock,
  274        /// Toggles centered layout mode.
  275        ToggleCenteredLayout,
  276        /// Toggles edit prediction feature globally for all files.
  277        ToggleEditPrediction,
  278        /// Toggles the left dock.
  279        ToggleLeftDock,
  280        /// Toggles the right dock.
  281        ToggleRightDock,
  282        /// Toggles zoom on the active pane.
  283        ToggleZoom,
  284        /// Toggles read-only mode for the active item (if supported by that item).
  285        ToggleReadOnlyFile,
  286        /// Zooms in on the active pane.
  287        ZoomIn,
  288        /// Zooms out of the active pane.
  289        ZoomOut,
  290        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  291        /// If the modal is shown already, closes it without trusting any worktree.
  292        ToggleWorktreeSecurity,
  293        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  294        /// Requires restart to take effect on already opened projects.
  295        ClearTrustedWorktrees,
  296        /// Stops following a collaborator.
  297        Unfollow,
  298        /// Restores the banner.
  299        RestoreBanner,
  300        /// Toggles expansion of the selected item.
  301        ToggleExpandItem,
  302    ]
  303);
  304
  305/// Activates a specific pane by its index.
  306#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  307#[action(namespace = workspace)]
  308pub struct ActivatePane(pub usize);
  309
  310/// Moves an item to a specific pane by index.
  311#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  312#[action(namespace = workspace)]
  313#[serde(deny_unknown_fields)]
  314pub struct MoveItemToPane {
  315    #[serde(default = "default_1")]
  316    pub destination: usize,
  317    #[serde(default = "default_true")]
  318    pub focus: bool,
  319    #[serde(default)]
  320    pub clone: bool,
  321}
  322
  323fn default_1() -> usize {
  324    1
  325}
  326
  327/// Moves an item to a pane in the specified direction.
  328#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  329#[action(namespace = workspace)]
  330#[serde(deny_unknown_fields)]
  331pub struct MoveItemToPaneInDirection {
  332    #[serde(default = "default_right")]
  333    pub direction: SplitDirection,
  334    #[serde(default = "default_true")]
  335    pub focus: bool,
  336    #[serde(default)]
  337    pub clone: bool,
  338}
  339
  340/// Creates a new file in a split of the desired direction.
  341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  342#[action(namespace = workspace)]
  343#[serde(deny_unknown_fields)]
  344pub struct NewFileSplit(pub SplitDirection);
  345
  346fn default_right() -> SplitDirection {
  347    SplitDirection::Right
  348}
  349
  350/// Saves all open files in the workspace.
  351#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  352#[action(namespace = workspace)]
  353#[serde(deny_unknown_fields)]
  354pub struct SaveAll {
  355    #[serde(default)]
  356    pub save_intent: Option<SaveIntent>,
  357}
  358
  359/// Saves the current file with the specified options.
  360#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  361#[action(namespace = workspace)]
  362#[serde(deny_unknown_fields)]
  363pub struct Save {
  364    #[serde(default)]
  365    pub save_intent: Option<SaveIntent>,
  366}
  367
  368/// Closes all items and panes in the workspace.
  369#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  370#[action(namespace = workspace)]
  371#[serde(deny_unknown_fields)]
  372pub struct CloseAllItemsAndPanes {
  373    #[serde(default)]
  374    pub save_intent: Option<SaveIntent>,
  375}
  376
  377/// Closes all inactive tabs and panes in the workspace.
  378#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  379#[action(namespace = workspace)]
  380#[serde(deny_unknown_fields)]
  381pub struct CloseInactiveTabsAndPanes {
  382    #[serde(default)]
  383    pub save_intent: Option<SaveIntent>,
  384}
  385
  386/// Sends a sequence of keystrokes to the active element.
  387#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  388#[action(namespace = workspace)]
  389pub struct SendKeystrokes(pub String);
  390
  391actions!(
  392    project_symbols,
  393    [
  394        /// Toggles the project symbols search.
  395        #[action(name = "Toggle")]
  396        ToggleProjectSymbols
  397    ]
  398);
  399
  400/// Toggles the file finder interface.
  401#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  402#[action(namespace = file_finder, name = "Toggle")]
  403#[serde(deny_unknown_fields)]
  404pub struct ToggleFileFinder {
  405    #[serde(default)]
  406    pub separate_history: bool,
  407}
  408
  409/// Increases size of a currently focused dock by a given amount of pixels.
  410#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  411#[action(namespace = workspace)]
  412#[serde(deny_unknown_fields)]
  413pub struct IncreaseActiveDockSize {
  414    /// For 0px parameter, uses UI font size value.
  415    #[serde(default)]
  416    pub px: u32,
  417}
  418
  419/// Decreases size of a currently focused dock by a given amount of pixels.
  420#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  421#[action(namespace = workspace)]
  422#[serde(deny_unknown_fields)]
  423pub struct DecreaseActiveDockSize {
  424    /// For 0px parameter, uses UI font size value.
  425    #[serde(default)]
  426    pub px: u32,
  427}
  428
  429/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  430#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  431#[action(namespace = workspace)]
  432#[serde(deny_unknown_fields)]
  433pub struct IncreaseOpenDocksSize {
  434    /// For 0px parameter, uses UI font size value.
  435    #[serde(default)]
  436    pub px: u32,
  437}
  438
  439/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  440#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  441#[action(namespace = workspace)]
  442#[serde(deny_unknown_fields)]
  443pub struct DecreaseOpenDocksSize {
  444    /// For 0px parameter, uses UI font size value.
  445    #[serde(default)]
  446    pub px: u32,
  447}
  448
  449actions!(
  450    workspace,
  451    [
  452        /// Activates the pane to the left.
  453        ActivatePaneLeft,
  454        /// Activates the pane to the right.
  455        ActivatePaneRight,
  456        /// Activates the pane above.
  457        ActivatePaneUp,
  458        /// Activates the pane below.
  459        ActivatePaneDown,
  460        /// Swaps the current pane with the one to the left.
  461        SwapPaneLeft,
  462        /// Swaps the current pane with the one to the right.
  463        SwapPaneRight,
  464        /// Swaps the current pane with the one above.
  465        SwapPaneUp,
  466        /// Swaps the current pane with the one below.
  467        SwapPaneDown,
  468        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  469        SwapPaneAdjacent,
  470        /// Move the current pane to be at the far left.
  471        MovePaneLeft,
  472        /// Move the current pane to be at the far right.
  473        MovePaneRight,
  474        /// Move the current pane to be at the very top.
  475        MovePaneUp,
  476        /// Move the current pane to be at the very bottom.
  477        MovePaneDown,
  478    ]
  479);
  480
  481#[derive(PartialEq, Eq, Debug)]
  482pub enum CloseIntent {
  483    /// Quit the program entirely.
  484    Quit,
  485    /// Close a window.
  486    CloseWindow,
  487    /// Replace the workspace in an existing window.
  488    ReplaceWindow,
  489}
  490
  491#[derive(Clone)]
  492pub struct Toast {
  493    id: NotificationId,
  494    msg: Cow<'static, str>,
  495    autohide: bool,
  496    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  497}
  498
  499impl Toast {
  500    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  501        Toast {
  502            id,
  503            msg: msg.into(),
  504            on_click: None,
  505            autohide: false,
  506        }
  507    }
  508
  509    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  510    where
  511        M: Into<Cow<'static, str>>,
  512        F: Fn(&mut Window, &mut App) + 'static,
  513    {
  514        self.on_click = Some((message.into(), Arc::new(on_click)));
  515        self
  516    }
  517
  518    pub fn autohide(mut self) -> Self {
  519        self.autohide = true;
  520        self
  521    }
  522}
  523
  524impl PartialEq for Toast {
  525    fn eq(&self, other: &Self) -> bool {
  526        self.id == other.id
  527            && self.msg == other.msg
  528            && self.on_click.is_some() == other.on_click.is_some()
  529    }
  530}
  531
  532/// Opens a new terminal with the specified working directory.
  533#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  534#[action(namespace = workspace)]
  535#[serde(deny_unknown_fields)]
  536pub struct OpenTerminal {
  537    pub working_directory: PathBuf,
  538}
  539
  540#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
  541pub struct WorkspaceId(i64);
  542
  543impl StaticColumnCount for WorkspaceId {}
  544impl Bind for WorkspaceId {
  545    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  546        self.0.bind(statement, start_index)
  547    }
  548}
  549impl Column for WorkspaceId {
  550    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  551        i64::column(statement, start_index)
  552            .map(|(i, next_index)| (Self(i), next_index))
  553            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  554    }
  555}
  556impl From<WorkspaceId> for i64 {
  557    fn from(val: WorkspaceId) -> Self {
  558        val.0
  559    }
  560}
  561
  562fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  563    let paths = cx.prompt_for_paths(options);
  564    cx.spawn(
  565        async move |cx| match paths.await.anyhow().and_then(|res| res) {
  566            Ok(Some(paths)) => {
  567                cx.update(|cx| {
  568                    open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
  569                })
  570                .ok();
  571            }
  572            Ok(None) => {}
  573            Err(err) => {
  574                util::log_err(&err);
  575                cx.update(|cx| {
  576                    if let Some(workspace_window) = cx
  577                        .active_window()
  578                        .and_then(|window| window.downcast::<Workspace>())
  579                    {
  580                        workspace_window
  581                            .update(cx, |workspace, _, cx| {
  582                                workspace.show_portal_error(err.to_string(), cx);
  583                            })
  584                            .ok();
  585                    }
  586                })
  587                .ok();
  588            }
  589        },
  590    )
  591    .detach();
  592}
  593
  594pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  595    component::init();
  596    theme_preview::init(cx);
  597    toast_layer::init(cx);
  598    history_manager::init(cx);
  599
  600    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  601        .on_action(|_: &Reload, cx| reload(cx))
  602        .on_action({
  603            let app_state = Arc::downgrade(&app_state);
  604            move |_: &Open, cx: &mut App| {
  605                if let Some(app_state) = app_state.upgrade() {
  606                    prompt_and_open_paths(
  607                        app_state,
  608                        PathPromptOptions {
  609                            files: true,
  610                            directories: true,
  611                            multiple: true,
  612                            prompt: None,
  613                        },
  614                        cx,
  615                    );
  616                }
  617            }
  618        })
  619        .on_action({
  620            let app_state = Arc::downgrade(&app_state);
  621            move |_: &OpenFiles, cx: &mut App| {
  622                let directories = cx.can_select_mixed_files_and_dirs();
  623                if let Some(app_state) = app_state.upgrade() {
  624                    prompt_and_open_paths(
  625                        app_state,
  626                        PathPromptOptions {
  627                            files: true,
  628                            directories,
  629                            multiple: true,
  630                            prompt: None,
  631                        },
  632                        cx,
  633                    );
  634                }
  635            }
  636        });
  637}
  638
  639type BuildProjectItemFn =
  640    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  641
  642type BuildProjectItemForPathFn =
  643    fn(
  644        &Entity<Project>,
  645        &ProjectPath,
  646        &mut Window,
  647        &mut App,
  648    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  649
  650#[derive(Clone, Default)]
  651struct ProjectItemRegistry {
  652    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  653    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  654}
  655
  656impl ProjectItemRegistry {
  657    fn register<T: ProjectItem>(&mut self) {
  658        self.build_project_item_fns_by_type.insert(
  659            TypeId::of::<T::Item>(),
  660            |item, project, pane, window, cx| {
  661                let item = item.downcast().unwrap();
  662                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  663                    as Box<dyn ItemHandle>
  664            },
  665        );
  666        self.build_project_item_for_path_fns
  667            .push(|project, project_path, window, cx| {
  668                let project_path = project_path.clone();
  669                let is_file = project
  670                    .read(cx)
  671                    .entry_for_path(&project_path, cx)
  672                    .is_some_and(|entry| entry.is_file());
  673                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  674                let is_local = project.read(cx).is_local();
  675                let project_item =
  676                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  677                let project = project.clone();
  678                Some(window.spawn(cx, async move |cx| {
  679                    match project_item.await.with_context(|| {
  680                        format!(
  681                            "opening project path {:?}",
  682                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  683                        )
  684                    }) {
  685                        Ok(project_item) => {
  686                            let project_item = project_item;
  687                            let project_entry_id: Option<ProjectEntryId> =
  688                                project_item.read_with(cx, project::ProjectItem::entry_id)?;
  689                            let build_workspace_item = Box::new(
  690                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  691                                    Box::new(cx.new(|cx| {
  692                                        T::for_project_item(
  693                                            project,
  694                                            Some(pane),
  695                                            project_item,
  696                                            window,
  697                                            cx,
  698                                        )
  699                                    })) as Box<dyn ItemHandle>
  700                                },
  701                            ) as Box<_>;
  702                            Ok((project_entry_id, build_workspace_item))
  703                        }
  704                        Err(e) => {
  705                            log::warn!("Failed to open a project item: {e:#}");
  706                            if e.error_code() == ErrorCode::Internal {
  707                                if let Some(abs_path) =
  708                                    entry_abs_path.as_deref().filter(|_| is_file)
  709                                {
  710                                    if let Some(broken_project_item_view) =
  711                                        cx.update(|window, cx| {
  712                                            T::for_broken_project_item(
  713                                                abs_path, is_local, &e, window, cx,
  714                                            )
  715                                        })?
  716                                    {
  717                                        let build_workspace_item = Box::new(
  718                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  719                                                cx.new(|_| broken_project_item_view).boxed_clone()
  720                                            },
  721                                        )
  722                                        as Box<_>;
  723                                        return Ok((None, build_workspace_item));
  724                                    }
  725                                }
  726                            }
  727                            Err(e)
  728                        }
  729                    }
  730                }))
  731            });
  732    }
  733
  734    fn open_path(
  735        &self,
  736        project: &Entity<Project>,
  737        path: &ProjectPath,
  738        window: &mut Window,
  739        cx: &mut App,
  740    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  741        let Some(open_project_item) = self
  742            .build_project_item_for_path_fns
  743            .iter()
  744            .rev()
  745            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  746        else {
  747            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  748        };
  749        open_project_item
  750    }
  751
  752    fn build_item<T: project::ProjectItem>(
  753        &self,
  754        item: Entity<T>,
  755        project: Entity<Project>,
  756        pane: Option<&Pane>,
  757        window: &mut Window,
  758        cx: &mut App,
  759    ) -> Option<Box<dyn ItemHandle>> {
  760        let build = self
  761            .build_project_item_fns_by_type
  762            .get(&TypeId::of::<T>())?;
  763        Some(build(item.into_any(), project, pane, window, cx))
  764    }
  765}
  766
  767type WorkspaceItemBuilder =
  768    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  769
  770impl Global for ProjectItemRegistry {}
  771
  772/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  773/// items will get a chance to open the file, starting from the project item that
  774/// was added last.
  775pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  776    cx.default_global::<ProjectItemRegistry>().register::<I>();
  777}
  778
  779#[derive(Default)]
  780pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  781
  782struct FollowableViewDescriptor {
  783    from_state_proto: fn(
  784        Entity<Workspace>,
  785        ViewId,
  786        &mut Option<proto::view::Variant>,
  787        &mut Window,
  788        &mut App,
  789    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  790    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  791}
  792
  793impl Global for FollowableViewRegistry {}
  794
  795impl FollowableViewRegistry {
  796    pub fn register<I: FollowableItem>(cx: &mut App) {
  797        cx.default_global::<Self>().0.insert(
  798            TypeId::of::<I>(),
  799            FollowableViewDescriptor {
  800                from_state_proto: |workspace, id, state, window, cx| {
  801                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  802                        cx.foreground_executor()
  803                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  804                    })
  805                },
  806                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  807            },
  808        );
  809    }
  810
  811    pub fn from_state_proto(
  812        workspace: Entity<Workspace>,
  813        view_id: ViewId,
  814        mut state: Option<proto::view::Variant>,
  815        window: &mut Window,
  816        cx: &mut App,
  817    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  818        cx.update_default_global(|this: &mut Self, cx| {
  819            this.0.values().find_map(|descriptor| {
  820                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  821            })
  822        })
  823    }
  824
  825    pub fn to_followable_view(
  826        view: impl Into<AnyView>,
  827        cx: &App,
  828    ) -> Option<Box<dyn FollowableItemHandle>> {
  829        let this = cx.try_global::<Self>()?;
  830        let view = view.into();
  831        let descriptor = this.0.get(&view.entity_type())?;
  832        Some((descriptor.to_followable_view)(&view))
  833    }
  834}
  835
  836#[derive(Copy, Clone)]
  837struct SerializableItemDescriptor {
  838    deserialize: fn(
  839        Entity<Project>,
  840        WeakEntity<Workspace>,
  841        WorkspaceId,
  842        ItemId,
  843        &mut Window,
  844        &mut Context<Pane>,
  845    ) -> Task<Result<Box<dyn ItemHandle>>>,
  846    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  847    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  848}
  849
  850#[derive(Default)]
  851struct SerializableItemRegistry {
  852    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  853    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  854}
  855
  856impl Global for SerializableItemRegistry {}
  857
  858impl SerializableItemRegistry {
  859    fn deserialize(
  860        item_kind: &str,
  861        project: Entity<Project>,
  862        workspace: WeakEntity<Workspace>,
  863        workspace_id: WorkspaceId,
  864        item_item: ItemId,
  865        window: &mut Window,
  866        cx: &mut Context<Pane>,
  867    ) -> Task<Result<Box<dyn ItemHandle>>> {
  868        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  869            return Task::ready(Err(anyhow!(
  870                "cannot deserialize {}, descriptor not found",
  871                item_kind
  872            )));
  873        };
  874
  875        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  876    }
  877
  878    fn cleanup(
  879        item_kind: &str,
  880        workspace_id: WorkspaceId,
  881        loaded_items: Vec<ItemId>,
  882        window: &mut Window,
  883        cx: &mut App,
  884    ) -> Task<Result<()>> {
  885        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  886            return Task::ready(Err(anyhow!(
  887                "cannot cleanup {}, descriptor not found",
  888                item_kind
  889            )));
  890        };
  891
  892        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  893    }
  894
  895    fn view_to_serializable_item_handle(
  896        view: AnyView,
  897        cx: &App,
  898    ) -> Option<Box<dyn SerializableItemHandle>> {
  899        let this = cx.try_global::<Self>()?;
  900        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  901        Some((descriptor.view_to_serializable_item)(view))
  902    }
  903
  904    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  905        let this = cx.try_global::<Self>()?;
  906        this.descriptors_by_kind.get(item_kind).copied()
  907    }
  908}
  909
  910pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  911    let serialized_item_kind = I::serialized_item_kind();
  912
  913    let registry = cx.default_global::<SerializableItemRegistry>();
  914    let descriptor = SerializableItemDescriptor {
  915        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  916            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  917            cx.foreground_executor()
  918                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  919        },
  920        cleanup: |workspace_id, loaded_items, window, cx| {
  921            I::cleanup(workspace_id, loaded_items, window, cx)
  922        },
  923        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
  924    };
  925    registry
  926        .descriptors_by_kind
  927        .insert(Arc::from(serialized_item_kind), descriptor);
  928    registry
  929        .descriptors_by_type
  930        .insert(TypeId::of::<I>(), descriptor);
  931}
  932
  933pub struct AppState {
  934    pub languages: Arc<LanguageRegistry>,
  935    pub client: Arc<Client>,
  936    pub user_store: Entity<UserStore>,
  937    pub workspace_store: Entity<WorkspaceStore>,
  938    pub fs: Arc<dyn fs::Fs>,
  939    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
  940    pub node_runtime: NodeRuntime,
  941    pub session: Entity<AppSession>,
  942}
  943
  944struct GlobalAppState(Weak<AppState>);
  945
  946impl Global for GlobalAppState {}
  947
  948pub struct WorkspaceStore {
  949    workspaces: HashSet<WindowHandle<Workspace>>,
  950    client: Arc<Client>,
  951    _subscriptions: Vec<client::Subscription>,
  952}
  953
  954#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
  955pub enum CollaboratorId {
  956    PeerId(PeerId),
  957    Agent,
  958}
  959
  960impl From<PeerId> for CollaboratorId {
  961    fn from(peer_id: PeerId) -> Self {
  962        CollaboratorId::PeerId(peer_id)
  963    }
  964}
  965
  966impl From<&PeerId> for CollaboratorId {
  967    fn from(peer_id: &PeerId) -> Self {
  968        CollaboratorId::PeerId(*peer_id)
  969    }
  970}
  971
  972#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
  973struct Follower {
  974    project_id: Option<u64>,
  975    peer_id: PeerId,
  976}
  977
  978impl AppState {
  979    #[track_caller]
  980    pub fn global(cx: &App) -> Weak<Self> {
  981        cx.global::<GlobalAppState>().0.clone()
  982    }
  983    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
  984        cx.try_global::<GlobalAppState>()
  985            .map(|state| state.0.clone())
  986    }
  987    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
  988        cx.set_global(GlobalAppState(state));
  989    }
  990
  991    #[cfg(any(test, feature = "test-support"))]
  992    pub fn test(cx: &mut App) -> Arc<Self> {
  993        use fs::Fs;
  994        use node_runtime::NodeRuntime;
  995        use session::Session;
  996        use settings::SettingsStore;
  997
  998        if !cx.has_global::<SettingsStore>() {
  999            let settings_store = SettingsStore::test(cx);
 1000            cx.set_global(settings_store);
 1001        }
 1002
 1003        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1004        <dyn Fs>::set_global(fs.clone(), cx);
 1005        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1006        let clock = Arc::new(clock::FakeSystemClock::new());
 1007        let http_client = http_client::FakeHttpClient::with_404_response();
 1008        let client = Client::new(clock, http_client, cx);
 1009        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1010        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1011        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1012
 1013        theme::init(theme::LoadThemes::JustBase, cx);
 1014        client::init(&client, cx);
 1015
 1016        Arc::new(Self {
 1017            client,
 1018            fs,
 1019            languages,
 1020            user_store,
 1021            workspace_store,
 1022            node_runtime: NodeRuntime::unavailable(),
 1023            build_window_options: |_, _| Default::default(),
 1024            session,
 1025        })
 1026    }
 1027}
 1028
 1029struct DelayedDebouncedEditAction {
 1030    task: Option<Task<()>>,
 1031    cancel_channel: Option<oneshot::Sender<()>>,
 1032}
 1033
 1034impl DelayedDebouncedEditAction {
 1035    fn new() -> DelayedDebouncedEditAction {
 1036        DelayedDebouncedEditAction {
 1037            task: None,
 1038            cancel_channel: None,
 1039        }
 1040    }
 1041
 1042    fn fire_new<F>(
 1043        &mut self,
 1044        delay: Duration,
 1045        window: &mut Window,
 1046        cx: &mut Context<Workspace>,
 1047        func: F,
 1048    ) where
 1049        F: 'static
 1050            + Send
 1051            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1052    {
 1053        if let Some(channel) = self.cancel_channel.take() {
 1054            _ = channel.send(());
 1055        }
 1056
 1057        let (sender, mut receiver) = oneshot::channel::<()>();
 1058        self.cancel_channel = Some(sender);
 1059
 1060        let previous_task = self.task.take();
 1061        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1062            let mut timer = cx.background_executor().timer(delay).fuse();
 1063            if let Some(previous_task) = previous_task {
 1064                previous_task.await;
 1065            }
 1066
 1067            futures::select_biased! {
 1068                _ = receiver => return,
 1069                    _ = timer => {}
 1070            }
 1071
 1072            if let Some(result) = workspace
 1073                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1074                .log_err()
 1075            {
 1076                result.await.log_err();
 1077            }
 1078        }));
 1079    }
 1080}
 1081
 1082pub enum Event {
 1083    PaneAdded(Entity<Pane>),
 1084    PaneRemoved,
 1085    ItemAdded {
 1086        item: Box<dyn ItemHandle>,
 1087    },
 1088    ActiveItemChanged,
 1089    ItemRemoved {
 1090        item_id: EntityId,
 1091    },
 1092    UserSavedItem {
 1093        pane: WeakEntity<Pane>,
 1094        item: Box<dyn WeakItemHandle>,
 1095        save_intent: SaveIntent,
 1096    },
 1097    ContactRequestedJoin(u64),
 1098    WorkspaceCreated(WeakEntity<Workspace>),
 1099    OpenBundledFile {
 1100        text: Cow<'static, str>,
 1101        title: &'static str,
 1102        language: &'static str,
 1103    },
 1104    ZoomChanged,
 1105    ModalOpened,
 1106}
 1107
 1108#[derive(Debug)]
 1109pub enum OpenVisible {
 1110    All,
 1111    None,
 1112    OnlyFiles,
 1113    OnlyDirectories,
 1114}
 1115
 1116enum WorkspaceLocation {
 1117    // Valid local paths or SSH project to serialize
 1118    Location(SerializedWorkspaceLocation, PathList),
 1119    // No valid location found hence clear session id
 1120    DetachFromSession,
 1121    // No valid location found to serialize
 1122    None,
 1123}
 1124
 1125type PromptForNewPath = Box<
 1126    dyn Fn(
 1127        &mut Workspace,
 1128        DirectoryLister,
 1129        &mut Window,
 1130        &mut Context<Workspace>,
 1131    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1132>;
 1133
 1134type PromptForOpenPath = Box<
 1135    dyn Fn(
 1136        &mut Workspace,
 1137        DirectoryLister,
 1138        &mut Window,
 1139        &mut Context<Workspace>,
 1140    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1141>;
 1142
 1143#[derive(Default)]
 1144struct DispatchingKeystrokes {
 1145    dispatched: HashSet<Vec<Keystroke>>,
 1146    queue: VecDeque<Keystroke>,
 1147    task: Option<Shared<Task<()>>>,
 1148}
 1149
 1150/// Collects everything project-related for a certain window opened.
 1151/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1152///
 1153/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1154/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1155/// that can be used to register a global action to be triggered from any place in the window.
 1156pub struct Workspace {
 1157    weak_self: WeakEntity<Self>,
 1158    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1159    zoomed: Option<AnyWeakView>,
 1160    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1161    zoomed_position: Option<DockPosition>,
 1162    center: PaneGroup,
 1163    left_dock: Entity<Dock>,
 1164    bottom_dock: Entity<Dock>,
 1165    right_dock: Entity<Dock>,
 1166    panes: Vec<Entity<Pane>>,
 1167    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1168    active_pane: Entity<Pane>,
 1169    last_active_center_pane: Option<WeakEntity<Pane>>,
 1170    last_active_view_id: Option<proto::ViewId>,
 1171    status_bar: Entity<StatusBar>,
 1172    modal_layer: Entity<ModalLayer>,
 1173    toast_layer: Entity<ToastLayer>,
 1174    titlebar_item: Option<AnyView>,
 1175    notifications: Notifications,
 1176    suppressed_notifications: HashSet<NotificationId>,
 1177    project: Entity<Project>,
 1178    follower_states: HashMap<CollaboratorId, FollowerState>,
 1179    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1180    window_edited: bool,
 1181    last_window_title: Option<String>,
 1182    dirty_items: HashMap<EntityId, Subscription>,
 1183    active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
 1184    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1185    database_id: Option<WorkspaceId>,
 1186    app_state: Arc<AppState>,
 1187    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1188    _subscriptions: Vec<Subscription>,
 1189    _apply_leader_updates: Task<Result<()>>,
 1190    _observe_current_user: Task<Result<()>>,
 1191    _schedule_serialize_workspace: Option<Task<()>>,
 1192    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1193    pane_history_timestamp: Arc<AtomicUsize>,
 1194    bounds: Bounds<Pixels>,
 1195    pub centered_layout: bool,
 1196    bounds_save_task_queued: Option<Task<()>>,
 1197    on_prompt_for_new_path: Option<PromptForNewPath>,
 1198    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1199    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1200    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1201    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1202    _items_serializer: Task<Result<()>>,
 1203    session_id: Option<String>,
 1204    scheduled_tasks: Vec<Task<()>>,
 1205    last_open_dock_positions: Vec<DockPosition>,
 1206    removing: bool,
 1207    utility_panes: UtilityPaneState,
 1208    next_modal_placement: Option<ModalPlacement>,
 1209}
 1210
 1211impl EventEmitter<Event> for Workspace {}
 1212
 1213#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1214pub struct ViewId {
 1215    pub creator: CollaboratorId,
 1216    pub id: u64,
 1217}
 1218
 1219pub struct FollowerState {
 1220    center_pane: Entity<Pane>,
 1221    dock_pane: Option<Entity<Pane>>,
 1222    active_view_id: Option<ViewId>,
 1223    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1224}
 1225
 1226struct FollowerView {
 1227    view: Box<dyn FollowableItemHandle>,
 1228    location: Option<proto::PanelId>,
 1229}
 1230
 1231impl Workspace {
 1232    pub fn new(
 1233        workspace_id: Option<WorkspaceId>,
 1234        project: Entity<Project>,
 1235        app_state: Arc<AppState>,
 1236        window: &mut Window,
 1237        cx: &mut Context<Self>,
 1238    ) -> Self {
 1239        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1240            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1241                if let TrustedWorktreesEvent::Trusted(..) = e {
 1242                    // Do not persist auto trusted worktrees
 1243                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1244                        worktrees_store.update(cx, |worktrees_store, cx| {
 1245                            worktrees_store.schedule_serialization(
 1246                                cx,
 1247                                |new_trusted_worktrees, cx| {
 1248                                    let timeout =
 1249                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1250                                    cx.background_spawn(async move {
 1251                                        timeout.await;
 1252                                        persistence::DB
 1253                                            .save_trusted_worktrees(new_trusted_worktrees)
 1254                                            .await
 1255                                            .log_err();
 1256                                    })
 1257                                },
 1258                            )
 1259                        });
 1260                    }
 1261                }
 1262            })
 1263            .detach();
 1264
 1265            cx.observe_global::<SettingsStore>(|_, cx| {
 1266                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1267                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1268                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1269                            trusted_worktrees.auto_trust_all(cx);
 1270                        })
 1271                    }
 1272                }
 1273            })
 1274            .detach();
 1275        }
 1276
 1277        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1278            match event {
 1279                project::Event::RemoteIdChanged(_) => {
 1280                    this.update_window_title(window, cx);
 1281                }
 1282
 1283                project::Event::CollaboratorLeft(peer_id) => {
 1284                    this.collaborator_left(*peer_id, window, cx);
 1285                }
 1286
 1287                project::Event::WorktreeUpdatedEntries(worktree_id, _) => {
 1288                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1289                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1290                            trusted_worktrees.can_trust(
 1291                                &this.project().read(cx).worktree_store(),
 1292                                *worktree_id,
 1293                                cx,
 1294                            );
 1295                        });
 1296                    }
 1297                }
 1298
 1299                project::Event::WorktreeRemoved(_) => {
 1300                    this.update_worktree_data(window, cx);
 1301                }
 1302
 1303                project::Event::WorktreeAdded(worktree_id) => {
 1304                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1305                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1306                            trusted_worktrees.can_trust(
 1307                                &this.project().read(cx).worktree_store(),
 1308                                *worktree_id,
 1309                                cx,
 1310                            );
 1311                        });
 1312                    }
 1313                    this.update_worktree_data(window, cx);
 1314                }
 1315
 1316                project::Event::DisconnectedFromHost => {
 1317                    this.update_window_edited(window, cx);
 1318                    let leaders_to_unfollow =
 1319                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1320                    for leader_id in leaders_to_unfollow {
 1321                        this.unfollow(leader_id, window, cx);
 1322                    }
 1323                }
 1324
 1325                project::Event::DisconnectedFromSshRemote => {
 1326                    this.update_window_edited(window, cx);
 1327                }
 1328
 1329                project::Event::Closed => {
 1330                    window.remove_window();
 1331                }
 1332
 1333                project::Event::DeletedEntry(_, entry_id) => {
 1334                    for pane in this.panes.iter() {
 1335                        pane.update(cx, |pane, cx| {
 1336                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1337                        });
 1338                    }
 1339                }
 1340
 1341                project::Event::Toast {
 1342                    notification_id,
 1343                    message,
 1344                } => this.show_notification(
 1345                    NotificationId::named(notification_id.clone()),
 1346                    cx,
 1347                    |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
 1348                ),
 1349
 1350                project::Event::HideToast { notification_id } => {
 1351                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1352                }
 1353
 1354                project::Event::LanguageServerPrompt(request) => {
 1355                    struct LanguageServerPrompt;
 1356
 1357                    let mut hasher = DefaultHasher::new();
 1358                    request.lsp_name.as_str().hash(&mut hasher);
 1359                    let id = hasher.finish();
 1360
 1361                    this.show_notification(
 1362                        NotificationId::composite::<LanguageServerPrompt>(id as usize),
 1363                        cx,
 1364                        |cx| {
 1365                            cx.new(|cx| {
 1366                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1367                            })
 1368                        },
 1369                    );
 1370                }
 1371
 1372                project::Event::AgentLocationChanged => {
 1373                    this.handle_agent_location_changed(window, cx)
 1374                }
 1375
 1376                _ => {}
 1377            }
 1378            cx.notify()
 1379        })
 1380        .detach();
 1381
 1382        cx.subscribe_in(
 1383            &project.read(cx).breakpoint_store(),
 1384            window,
 1385            |workspace, _, event, window, cx| match event {
 1386                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1387                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1388                    workspace.serialize_workspace(window, cx);
 1389                }
 1390                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1391            },
 1392        )
 1393        .detach();
 1394        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1395            cx.subscribe_in(
 1396                &toolchain_store,
 1397                window,
 1398                |workspace, _, event, window, cx| match event {
 1399                    ToolchainStoreEvent::CustomToolchainsModified => {
 1400                        workspace.serialize_workspace(window, cx);
 1401                    }
 1402                    _ => {}
 1403                },
 1404            )
 1405            .detach();
 1406        }
 1407
 1408        cx.on_focus_lost(window, |this, window, cx| {
 1409            let focus_handle = this.focus_handle(cx);
 1410            window.focus(&focus_handle, cx);
 1411        })
 1412        .detach();
 1413
 1414        let weak_handle = cx.entity().downgrade();
 1415        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1416
 1417        let center_pane = cx.new(|cx| {
 1418            let mut center_pane = Pane::new(
 1419                weak_handle.clone(),
 1420                project.clone(),
 1421                pane_history_timestamp.clone(),
 1422                None,
 1423                NewFile.boxed_clone(),
 1424                true,
 1425                window,
 1426                cx,
 1427            );
 1428            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1429            center_pane
 1430        });
 1431        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1432            .detach();
 1433
 1434        window.focus(&center_pane.focus_handle(cx), cx);
 1435
 1436        cx.emit(Event::PaneAdded(center_pane.clone()));
 1437
 1438        let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
 1439        app_state.workspace_store.update(cx, |store, _| {
 1440            store.workspaces.insert(window_handle);
 1441        });
 1442
 1443        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1444        let mut connection_status = app_state.client.status();
 1445        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1446            current_user.next().await;
 1447            connection_status.next().await;
 1448            let mut stream =
 1449                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1450
 1451            while stream.recv().await.is_some() {
 1452                this.update(cx, |_, cx| cx.notify())?;
 1453            }
 1454            anyhow::Ok(())
 1455        });
 1456
 1457        // All leader updates are enqueued and then processed in a single task, so
 1458        // that each asynchronous operation can be run in order.
 1459        let (leader_updates_tx, mut leader_updates_rx) =
 1460            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1461        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1462            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1463                Self::process_leader_update(&this, leader_id, update, cx)
 1464                    .await
 1465                    .log_err();
 1466            }
 1467
 1468            Ok(())
 1469        });
 1470
 1471        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1472        let modal_layer = cx.new(|_| ModalLayer::new());
 1473        let toast_layer = cx.new(|_| ToastLayer::new());
 1474        cx.subscribe(
 1475            &modal_layer,
 1476            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1477                cx.emit(Event::ModalOpened);
 1478            },
 1479        )
 1480        .detach();
 1481
 1482        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1483        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1484        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1485        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1486        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1487        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1488        let status_bar = cx.new(|cx| {
 1489            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1490            status_bar.add_left_item(left_dock_buttons, window, cx);
 1491            status_bar.add_right_item(right_dock_buttons, window, cx);
 1492            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1493            status_bar
 1494        });
 1495
 1496        let session_id = app_state.session.read(cx).id().to_owned();
 1497
 1498        let mut active_call = None;
 1499        if let Some(call) = ActiveCall::try_global(cx) {
 1500            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1501            active_call = Some((call, subscriptions));
 1502        }
 1503
 1504        let (serializable_items_tx, serializable_items_rx) =
 1505            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1506        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1507            Self::serialize_items(&this, serializable_items_rx, cx).await
 1508        });
 1509
 1510        let subscriptions = vec![
 1511            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1512            cx.observe_window_bounds(window, move |this, window, cx| {
 1513                if this.bounds_save_task_queued.is_some() {
 1514                    return;
 1515                }
 1516                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1517                    cx.background_executor()
 1518                        .timer(Duration::from_millis(100))
 1519                        .await;
 1520                    this.update_in(cx, |this, window, cx| {
 1521                        if let Some(display) = window.display(cx)
 1522                            && let Ok(display_uuid) = display.uuid()
 1523                        {
 1524                            let window_bounds = window.inner_window_bounds();
 1525                            let has_paths = !this.root_paths(cx).is_empty();
 1526                            if !has_paths {
 1527                                cx.background_executor()
 1528                                    .spawn(persistence::write_default_window_bounds(
 1529                                        window_bounds,
 1530                                        display_uuid,
 1531                                    ))
 1532                                    .detach_and_log_err(cx);
 1533                            }
 1534                            if let Some(database_id) = workspace_id {
 1535                                cx.background_executor()
 1536                                    .spawn(DB.set_window_open_status(
 1537                                        database_id,
 1538                                        SerializedWindowBounds(window_bounds),
 1539                                        display_uuid,
 1540                                    ))
 1541                                    .detach_and_log_err(cx);
 1542                            } else {
 1543                                cx.background_executor()
 1544                                    .spawn(persistence::write_default_window_bounds(
 1545                                        window_bounds,
 1546                                        display_uuid,
 1547                                    ))
 1548                                    .detach_and_log_err(cx);
 1549                            }
 1550                        }
 1551                        this.bounds_save_task_queued.take();
 1552                    })
 1553                    .ok();
 1554                }));
 1555                cx.notify();
 1556            }),
 1557            cx.observe_window_appearance(window, |_, window, cx| {
 1558                let window_appearance = window.appearance();
 1559
 1560                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1561
 1562                GlobalTheme::reload_theme(cx);
 1563                GlobalTheme::reload_icon_theme(cx);
 1564            }),
 1565            cx.on_release(move |this, cx| {
 1566                this.app_state.workspace_store.update(cx, move |store, _| {
 1567                    store.workspaces.remove(&window_handle);
 1568                })
 1569            }),
 1570        ];
 1571
 1572        cx.defer_in(window, move |this, window, cx| {
 1573            this.update_window_title(window, cx);
 1574            this.show_initial_notifications(cx);
 1575        });
 1576
 1577        let mut center = PaneGroup::new(center_pane.clone());
 1578        center.set_is_center(true);
 1579        center.mark_positions(cx);
 1580
 1581        Workspace {
 1582            weak_self: weak_handle.clone(),
 1583            zoomed: None,
 1584            zoomed_position: None,
 1585            previous_dock_drag_coordinates: None,
 1586            center,
 1587            panes: vec![center_pane.clone()],
 1588            panes_by_item: Default::default(),
 1589            active_pane: center_pane.clone(),
 1590            last_active_center_pane: Some(center_pane.downgrade()),
 1591            last_active_view_id: None,
 1592            status_bar,
 1593            modal_layer,
 1594            toast_layer,
 1595            titlebar_item: None,
 1596            notifications: Notifications::default(),
 1597            suppressed_notifications: HashSet::default(),
 1598            left_dock,
 1599            bottom_dock,
 1600            right_dock,
 1601            project: project.clone(),
 1602            follower_states: Default::default(),
 1603            last_leaders_by_pane: Default::default(),
 1604            dispatching_keystrokes: Default::default(),
 1605            window_edited: false,
 1606            last_window_title: None,
 1607            dirty_items: Default::default(),
 1608            active_call,
 1609            database_id: workspace_id,
 1610            app_state,
 1611            _observe_current_user,
 1612            _apply_leader_updates,
 1613            _schedule_serialize_workspace: None,
 1614            _schedule_serialize_ssh_paths: None,
 1615            leader_updates_tx,
 1616            _subscriptions: subscriptions,
 1617            pane_history_timestamp,
 1618            workspace_actions: Default::default(),
 1619            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1620            bounds: Default::default(),
 1621            centered_layout: false,
 1622            bounds_save_task_queued: None,
 1623            on_prompt_for_new_path: None,
 1624            on_prompt_for_open_path: None,
 1625            terminal_provider: None,
 1626            debugger_provider: None,
 1627            serializable_items_tx,
 1628            _items_serializer,
 1629            session_id: Some(session_id),
 1630
 1631            scheduled_tasks: Vec::new(),
 1632            last_open_dock_positions: Vec::new(),
 1633            removing: false,
 1634            utility_panes: UtilityPaneState::default(),
 1635            next_modal_placement: None,
 1636        }
 1637    }
 1638
 1639    pub fn new_local(
 1640        abs_paths: Vec<PathBuf>,
 1641        app_state: Arc<AppState>,
 1642        requesting_window: Option<WindowHandle<Workspace>>,
 1643        env: Option<HashMap<String, String>>,
 1644        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1645        cx: &mut App,
 1646    ) -> Task<
 1647        anyhow::Result<(
 1648            WindowHandle<Workspace>,
 1649            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1650        )>,
 1651    > {
 1652        let project_handle = Project::local(
 1653            app_state.client.clone(),
 1654            app_state.node_runtime.clone(),
 1655            app_state.user_store.clone(),
 1656            app_state.languages.clone(),
 1657            app_state.fs.clone(),
 1658            env,
 1659            true,
 1660            cx,
 1661        );
 1662
 1663        cx.spawn(async move |cx| {
 1664            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1665            for path in abs_paths.into_iter() {
 1666                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1667                    paths_to_open.push(canonical)
 1668                } else {
 1669                    paths_to_open.push(path)
 1670                }
 1671            }
 1672
 1673            let serialized_workspace =
 1674                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1675
 1676            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1677                paths_to_open = paths.ordered_paths().cloned().collect();
 1678                if !paths.is_lexicographically_ordered() {
 1679                    project_handle
 1680                        .update(cx, |project, cx| {
 1681                            project.set_worktrees_reordered(true, cx);
 1682                        })
 1683                        .log_err();
 1684                }
 1685            }
 1686
 1687            // Get project paths for all of the abs_paths
 1688            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1689                Vec::with_capacity(paths_to_open.len());
 1690
 1691            for path in paths_to_open.into_iter() {
 1692                if let Some((_, project_entry)) = cx
 1693                    .update(|cx| {
 1694                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1695                    })?
 1696                    .await
 1697                    .log_err()
 1698                {
 1699                    project_paths.push((path, Some(project_entry)));
 1700                } else {
 1701                    project_paths.push((path, None));
 1702                }
 1703            }
 1704
 1705            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1706                serialized_workspace.id
 1707            } else {
 1708                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1709            };
 1710
 1711            let toolchains = DB.toolchains(workspace_id).await?;
 1712
 1713            for (toolchain, worktree_path, path) in toolchains {
 1714                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1715                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1716                    this.find_worktree(&worktree_path, cx)
 1717                        .and_then(|(worktree, rel_path)| {
 1718                            if rel_path.is_empty() {
 1719                                Some(worktree.read(cx).id())
 1720                            } else {
 1721                                None
 1722                            }
 1723                        })
 1724                })?
 1725                else {
 1726                    // We did not find a worktree with a given path, but that's whatever.
 1727                    continue;
 1728                };
 1729                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1730                    continue;
 1731                }
 1732
 1733                project_handle
 1734                    .update(cx, |this, cx| {
 1735                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1736                    })?
 1737                    .await;
 1738            }
 1739            if let Some(workspace) = serialized_workspace.as_ref() {
 1740                project_handle.update(cx, |this, cx| {
 1741                    for (scope, toolchains) in &workspace.user_toolchains {
 1742                        for toolchain in toolchains {
 1743                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1744                        }
 1745                    }
 1746                })?;
 1747            }
 1748
 1749            let window = if let Some(window) = requesting_window {
 1750                let centered_layout = serialized_workspace
 1751                    .as_ref()
 1752                    .map(|w| w.centered_layout)
 1753                    .unwrap_or(false);
 1754
 1755                cx.update_window(window.into(), |_, window, cx| {
 1756                    window.replace_root(cx, |window, cx| {
 1757                        let mut workspace = Workspace::new(
 1758                            Some(workspace_id),
 1759                            project_handle.clone(),
 1760                            app_state.clone(),
 1761                            window,
 1762                            cx,
 1763                        );
 1764
 1765                        workspace.centered_layout = centered_layout;
 1766
 1767                        // Call init callback to add items before window renders
 1768                        if let Some(init) = init {
 1769                            init(&mut workspace, window, cx);
 1770                        }
 1771
 1772                        workspace
 1773                    });
 1774                })?;
 1775                window
 1776            } else {
 1777                let window_bounds_override = window_bounds_env_override();
 1778
 1779                let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1780                    (Some(WindowBounds::Windowed(bounds)), None)
 1781                } else if let Some(workspace) = serialized_workspace.as_ref()
 1782                    && let Some(display) = workspace.display
 1783                    && let Some(bounds) = workspace.window_bounds.as_ref()
 1784                {
 1785                    // Reopening an existing workspace - restore its saved bounds
 1786                    (Some(bounds.0), Some(display))
 1787                } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 1788                    // New or empty workspace - use the last known window bounds
 1789                    (Some(bounds), Some(display))
 1790                } else {
 1791                    // New window - let GPUI's default_bounds() handle cascading
 1792                    (None, None)
 1793                };
 1794
 1795                // Use the serialized workspace to construct the new window
 1796                let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
 1797                options.window_bounds = window_bounds;
 1798                let centered_layout = serialized_workspace
 1799                    .as_ref()
 1800                    .map(|w| w.centered_layout)
 1801                    .unwrap_or(false);
 1802                cx.open_window(options, {
 1803                    let app_state = app_state.clone();
 1804                    let project_handle = project_handle.clone();
 1805                    move |window, cx| {
 1806                        cx.new(|cx| {
 1807                            let mut workspace = Workspace::new(
 1808                                Some(workspace_id),
 1809                                project_handle,
 1810                                app_state,
 1811                                window,
 1812                                cx,
 1813                            );
 1814                            workspace.centered_layout = centered_layout;
 1815
 1816                            // Call init callback to add items before window renders
 1817                            if let Some(init) = init {
 1818                                init(&mut workspace, window, cx);
 1819                            }
 1820
 1821                            workspace
 1822                        })
 1823                    }
 1824                })?
 1825            };
 1826
 1827            notify_if_database_failed(window, cx);
 1828            let opened_items = window
 1829                .update(cx, |_workspace, window, cx| {
 1830                    open_items(serialized_workspace, project_paths, window, cx)
 1831                })?
 1832                .await
 1833                .unwrap_or_default();
 1834
 1835            window
 1836                .update(cx, |workspace, window, cx| {
 1837                    window.activate_window();
 1838                    workspace.update_history(cx);
 1839                })
 1840                .log_err();
 1841            Ok((window, opened_items))
 1842        })
 1843    }
 1844
 1845    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1846        self.weak_self.clone()
 1847    }
 1848
 1849    pub fn left_dock(&self) -> &Entity<Dock> {
 1850        &self.left_dock
 1851    }
 1852
 1853    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1854        &self.bottom_dock
 1855    }
 1856
 1857    pub fn set_bottom_dock_layout(
 1858        &mut self,
 1859        layout: BottomDockLayout,
 1860        window: &mut Window,
 1861        cx: &mut Context<Self>,
 1862    ) {
 1863        let fs = self.project().read(cx).fs();
 1864        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1865            content.workspace.bottom_dock_layout = Some(layout);
 1866        });
 1867
 1868        cx.notify();
 1869        self.serialize_workspace(window, cx);
 1870    }
 1871
 1872    pub fn right_dock(&self) -> &Entity<Dock> {
 1873        &self.right_dock
 1874    }
 1875
 1876    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1877        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1878    }
 1879
 1880    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1881        match position {
 1882            DockPosition::Left => &self.left_dock,
 1883            DockPosition::Bottom => &self.bottom_dock,
 1884            DockPosition::Right => &self.right_dock,
 1885        }
 1886    }
 1887
 1888    pub fn is_edited(&self) -> bool {
 1889        self.window_edited
 1890    }
 1891
 1892    pub fn add_panel<T: Panel>(
 1893        &mut self,
 1894        panel: Entity<T>,
 1895        window: &mut Window,
 1896        cx: &mut Context<Self>,
 1897    ) {
 1898        let focus_handle = panel.panel_focus_handle(cx);
 1899        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 1900            .detach();
 1901
 1902        let dock_position = panel.position(window, cx);
 1903        let dock = self.dock_at_position(dock_position);
 1904
 1905        dock.update(cx, |dock, cx| {
 1906            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 1907        });
 1908    }
 1909
 1910    pub fn remove_panel<T: Panel>(
 1911        &mut self,
 1912        panel: &Entity<T>,
 1913        window: &mut Window,
 1914        cx: &mut Context<Self>,
 1915    ) {
 1916        let mut found_in_dock = None;
 1917        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 1918            let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 1919
 1920            if found {
 1921                found_in_dock = Some(dock.clone());
 1922            }
 1923        }
 1924        if let Some(found_in_dock) = found_in_dock {
 1925            let position = found_in_dock.read(cx).position();
 1926            let slot = utility_slot_for_dock_position(position);
 1927            self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
 1928        }
 1929    }
 1930
 1931    pub fn status_bar(&self) -> &Entity<StatusBar> {
 1932        &self.status_bar
 1933    }
 1934
 1935    pub fn status_bar_visible(&self, cx: &App) -> bool {
 1936        StatusBarSettings::get_global(cx).show
 1937    }
 1938
 1939    pub fn app_state(&self) -> &Arc<AppState> {
 1940        &self.app_state
 1941    }
 1942
 1943    pub fn user_store(&self) -> &Entity<UserStore> {
 1944        &self.app_state.user_store
 1945    }
 1946
 1947    pub fn project(&self) -> &Entity<Project> {
 1948        &self.project
 1949    }
 1950
 1951    pub fn path_style(&self, cx: &App) -> PathStyle {
 1952        self.project.read(cx).path_style(cx)
 1953    }
 1954
 1955    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 1956        let mut history: HashMap<EntityId, usize> = HashMap::default();
 1957
 1958        for pane_handle in &self.panes {
 1959            let pane = pane_handle.read(cx);
 1960
 1961            for entry in pane.activation_history() {
 1962                history.insert(
 1963                    entry.entity_id,
 1964                    history
 1965                        .get(&entry.entity_id)
 1966                        .cloned()
 1967                        .unwrap_or(0)
 1968                        .max(entry.timestamp),
 1969                );
 1970            }
 1971        }
 1972
 1973        history
 1974    }
 1975
 1976    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 1977        let mut recent_item: Option<Entity<T>> = None;
 1978        let mut recent_timestamp = 0;
 1979        for pane_handle in &self.panes {
 1980            let pane = pane_handle.read(cx);
 1981            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 1982                pane.items().map(|item| (item.item_id(), item)).collect();
 1983            for entry in pane.activation_history() {
 1984                if entry.timestamp > recent_timestamp
 1985                    && let Some(&item) = item_map.get(&entry.entity_id)
 1986                    && let Some(typed_item) = item.act_as::<T>(cx)
 1987                {
 1988                    recent_timestamp = entry.timestamp;
 1989                    recent_item = Some(typed_item);
 1990                }
 1991            }
 1992        }
 1993        recent_item
 1994    }
 1995
 1996    pub fn recent_navigation_history_iter(
 1997        &self,
 1998        cx: &App,
 1999    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2000        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2001        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2002
 2003        for pane in &self.panes {
 2004            let pane = pane.read(cx);
 2005
 2006            pane.nav_history()
 2007                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 2008                    if let Some(fs_path) = &fs_path {
 2009                        abs_paths_opened
 2010                            .entry(fs_path.clone())
 2011                            .or_default()
 2012                            .insert(project_path.clone());
 2013                    }
 2014                    let timestamp = entry.timestamp;
 2015                    match history.entry(project_path) {
 2016                        hash_map::Entry::Occupied(mut entry) => {
 2017                            let (_, old_timestamp) = entry.get();
 2018                            if &timestamp > old_timestamp {
 2019                                entry.insert((fs_path, timestamp));
 2020                            }
 2021                        }
 2022                        hash_map::Entry::Vacant(entry) => {
 2023                            entry.insert((fs_path, timestamp));
 2024                        }
 2025                    }
 2026                });
 2027
 2028            if let Some(item) = pane.active_item()
 2029                && let Some(project_path) = item.project_path(cx)
 2030            {
 2031                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2032
 2033                if let Some(fs_path) = &fs_path {
 2034                    abs_paths_opened
 2035                        .entry(fs_path.clone())
 2036                        .or_default()
 2037                        .insert(project_path.clone());
 2038                }
 2039
 2040                history.insert(project_path, (fs_path, std::usize::MAX));
 2041            }
 2042        }
 2043
 2044        history
 2045            .into_iter()
 2046            .sorted_by_key(|(_, (_, order))| *order)
 2047            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2048            .rev()
 2049            .filter(move |(history_path, abs_path)| {
 2050                let latest_project_path_opened = abs_path
 2051                    .as_ref()
 2052                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2053                    .and_then(|project_paths| {
 2054                        project_paths
 2055                            .iter()
 2056                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2057                    });
 2058
 2059                latest_project_path_opened.is_none_or(|path| path == history_path)
 2060            })
 2061    }
 2062
 2063    pub fn recent_navigation_history(
 2064        &self,
 2065        limit: Option<usize>,
 2066        cx: &App,
 2067    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2068        self.recent_navigation_history_iter(cx)
 2069            .take(limit.unwrap_or(usize::MAX))
 2070            .collect()
 2071    }
 2072
 2073    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2074        for pane in &self.panes {
 2075            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2076        }
 2077    }
 2078
 2079    fn navigate_history(
 2080        &mut self,
 2081        pane: WeakEntity<Pane>,
 2082        mode: NavigationMode,
 2083        window: &mut Window,
 2084        cx: &mut Context<Workspace>,
 2085    ) -> Task<Result<()>> {
 2086        let to_load = if let Some(pane) = pane.upgrade() {
 2087            pane.update(cx, |pane, cx| {
 2088                window.focus(&pane.focus_handle(cx), cx);
 2089                loop {
 2090                    // Retrieve the weak item handle from the history.
 2091                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 2092
 2093                    // If the item is still present in this pane, then activate it.
 2094                    if let Some(index) = entry
 2095                        .item
 2096                        .upgrade()
 2097                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2098                    {
 2099                        let prev_active_item_index = pane.active_item_index();
 2100                        pane.nav_history_mut().set_mode(mode);
 2101                        pane.activate_item(index, true, true, window, cx);
 2102                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2103
 2104                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2105                        if let Some(data) = entry.data {
 2106                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2107                        }
 2108
 2109                        if navigated {
 2110                            break None;
 2111                        }
 2112                    } else {
 2113                        // If the item is no longer present in this pane, then retrieve its
 2114                        // path info in order to reopen it.
 2115                        break pane
 2116                            .nav_history()
 2117                            .path_for_item(entry.item.id())
 2118                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2119                    }
 2120                }
 2121            })
 2122        } else {
 2123            None
 2124        };
 2125
 2126        if let Some((project_path, abs_path, entry)) = to_load {
 2127            // If the item was no longer present, then load it again from its previous path, first try the local path
 2128            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2129
 2130            cx.spawn_in(window, async move  |workspace, cx| {
 2131                let open_by_project_path = open_by_project_path.await;
 2132                let mut navigated = false;
 2133                match open_by_project_path
 2134                    .with_context(|| format!("Navigating to {project_path:?}"))
 2135                {
 2136                    Ok((project_entry_id, build_item)) => {
 2137                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2138                            pane.nav_history_mut().set_mode(mode);
 2139                            pane.active_item().map(|p| p.item_id())
 2140                        })?;
 2141
 2142                        pane.update_in(cx, |pane, window, cx| {
 2143                            let item = pane.open_item(
 2144                                project_entry_id,
 2145                                project_path,
 2146                                true,
 2147                                entry.is_preview,
 2148                                true,
 2149                                None,
 2150                                window, cx,
 2151                                build_item,
 2152                            );
 2153                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2154                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2155                            if let Some(data) = entry.data {
 2156                                navigated |= item.navigate(data, window, cx);
 2157                            }
 2158                        })?;
 2159                    }
 2160                    Err(open_by_project_path_e) => {
 2161                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2162                        // and its worktree is now dropped
 2163                        if let Some(abs_path) = abs_path {
 2164                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2165                                pane.nav_history_mut().set_mode(mode);
 2166                                pane.active_item().map(|p| p.item_id())
 2167                            })?;
 2168                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2169                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2170                            })?;
 2171                            match open_by_abs_path
 2172                                .await
 2173                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2174                            {
 2175                                Ok(item) => {
 2176                                    pane.update_in(cx, |pane, window, cx| {
 2177                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2178                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2179                                        if let Some(data) = entry.data {
 2180                                            navigated |= item.navigate(data, window, cx);
 2181                                        }
 2182                                    })?;
 2183                                }
 2184                                Err(open_by_abs_path_e) => {
 2185                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2186                                }
 2187                            }
 2188                        }
 2189                    }
 2190                }
 2191
 2192                if !navigated {
 2193                    workspace
 2194                        .update_in(cx, |workspace, window, cx| {
 2195                            Self::navigate_history(workspace, pane, mode, window, cx)
 2196                        })?
 2197                        .await?;
 2198                }
 2199
 2200                Ok(())
 2201            })
 2202        } else {
 2203            Task::ready(Ok(()))
 2204        }
 2205    }
 2206
 2207    pub fn go_back(
 2208        &mut self,
 2209        pane: WeakEntity<Pane>,
 2210        window: &mut Window,
 2211        cx: &mut Context<Workspace>,
 2212    ) -> Task<Result<()>> {
 2213        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2214    }
 2215
 2216    pub fn go_forward(
 2217        &mut self,
 2218        pane: WeakEntity<Pane>,
 2219        window: &mut Window,
 2220        cx: &mut Context<Workspace>,
 2221    ) -> Task<Result<()>> {
 2222        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2223    }
 2224
 2225    pub fn reopen_closed_item(
 2226        &mut self,
 2227        window: &mut Window,
 2228        cx: &mut Context<Workspace>,
 2229    ) -> Task<Result<()>> {
 2230        self.navigate_history(
 2231            self.active_pane().downgrade(),
 2232            NavigationMode::ReopeningClosedItem,
 2233            window,
 2234            cx,
 2235        )
 2236    }
 2237
 2238    pub fn client(&self) -> &Arc<Client> {
 2239        &self.app_state.client
 2240    }
 2241
 2242    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2243        self.titlebar_item = Some(item);
 2244        cx.notify();
 2245    }
 2246
 2247    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2248        self.on_prompt_for_new_path = Some(prompt)
 2249    }
 2250
 2251    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2252        self.on_prompt_for_open_path = Some(prompt)
 2253    }
 2254
 2255    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2256        self.terminal_provider = Some(Box::new(provider));
 2257    }
 2258
 2259    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2260        self.debugger_provider = Some(Arc::new(provider));
 2261    }
 2262
 2263    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2264        self.debugger_provider.clone()
 2265    }
 2266
 2267    pub fn prompt_for_open_path(
 2268        &mut self,
 2269        path_prompt_options: PathPromptOptions,
 2270        lister: DirectoryLister,
 2271        window: &mut Window,
 2272        cx: &mut Context<Self>,
 2273    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2274        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2275            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2276            let rx = prompt(self, lister, window, cx);
 2277            self.on_prompt_for_open_path = Some(prompt);
 2278            rx
 2279        } else {
 2280            let (tx, rx) = oneshot::channel();
 2281            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2282
 2283            cx.spawn_in(window, async move |workspace, cx| {
 2284                let Ok(result) = abs_path.await else {
 2285                    return Ok(());
 2286                };
 2287
 2288                match result {
 2289                    Ok(result) => {
 2290                        tx.send(result).ok();
 2291                    }
 2292                    Err(err) => {
 2293                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2294                            workspace.show_portal_error(err.to_string(), cx);
 2295                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2296                            let rx = prompt(workspace, lister, window, cx);
 2297                            workspace.on_prompt_for_open_path = Some(prompt);
 2298                            rx
 2299                        })?;
 2300                        if let Ok(path) = rx.await {
 2301                            tx.send(path).ok();
 2302                        }
 2303                    }
 2304                };
 2305                anyhow::Ok(())
 2306            })
 2307            .detach();
 2308
 2309            rx
 2310        }
 2311    }
 2312
 2313    pub fn prompt_for_new_path(
 2314        &mut self,
 2315        lister: DirectoryLister,
 2316        suggested_name: Option<String>,
 2317        window: &mut Window,
 2318        cx: &mut Context<Self>,
 2319    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2320        if self.project.read(cx).is_via_collab()
 2321            || self.project.read(cx).is_via_remote_server()
 2322            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2323        {
 2324            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2325            let rx = prompt(self, lister, window, cx);
 2326            self.on_prompt_for_new_path = Some(prompt);
 2327            return rx;
 2328        }
 2329
 2330        let (tx, rx) = oneshot::channel();
 2331        cx.spawn_in(window, async move |workspace, cx| {
 2332            let abs_path = workspace.update(cx, |workspace, cx| {
 2333                let relative_to = workspace
 2334                    .most_recent_active_path(cx)
 2335                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2336                    .or_else(|| {
 2337                        let project = workspace.project.read(cx);
 2338                        project.visible_worktrees(cx).find_map(|worktree| {
 2339                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2340                        })
 2341                    })
 2342                    .or_else(std::env::home_dir)
 2343                    .unwrap_or_else(|| PathBuf::from(""));
 2344                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2345            })?;
 2346            let abs_path = match abs_path.await? {
 2347                Ok(path) => path,
 2348                Err(err) => {
 2349                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2350                        workspace.show_portal_error(err.to_string(), cx);
 2351
 2352                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2353                        let rx = prompt(workspace, lister, window, cx);
 2354                        workspace.on_prompt_for_new_path = Some(prompt);
 2355                        rx
 2356                    })?;
 2357                    if let Ok(path) = rx.await {
 2358                        tx.send(path).ok();
 2359                    }
 2360                    return anyhow::Ok(());
 2361                }
 2362            };
 2363
 2364            tx.send(abs_path.map(|path| vec![path])).ok();
 2365            anyhow::Ok(())
 2366        })
 2367        .detach();
 2368
 2369        rx
 2370    }
 2371
 2372    pub fn titlebar_item(&self) -> Option<AnyView> {
 2373        self.titlebar_item.clone()
 2374    }
 2375
 2376    /// Call the given callback with a workspace whose project is local.
 2377    ///
 2378    /// If the given workspace has a local project, then it will be passed
 2379    /// to the callback. Otherwise, a new empty window will be created.
 2380    pub fn with_local_workspace<T, F>(
 2381        &mut self,
 2382        window: &mut Window,
 2383        cx: &mut Context<Self>,
 2384        callback: F,
 2385    ) -> Task<Result<T>>
 2386    where
 2387        T: 'static,
 2388        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2389    {
 2390        if self.project.read(cx).is_local() {
 2391            Task::ready(Ok(callback(self, window, cx)))
 2392        } else {
 2393            let env = self.project.read(cx).cli_environment(cx);
 2394            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2395            cx.spawn_in(window, async move |_vh, cx| {
 2396                let (workspace, _) = task.await?;
 2397                workspace.update(cx, callback)
 2398            })
 2399        }
 2400    }
 2401
 2402    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2403        self.project.read(cx).worktrees(cx)
 2404    }
 2405
 2406    pub fn visible_worktrees<'a>(
 2407        &self,
 2408        cx: &'a App,
 2409    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2410        self.project.read(cx).visible_worktrees(cx)
 2411    }
 2412
 2413    #[cfg(any(test, feature = "test-support"))]
 2414    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2415        let futures = self
 2416            .worktrees(cx)
 2417            .filter_map(|worktree| worktree.read(cx).as_local())
 2418            .map(|worktree| worktree.scan_complete())
 2419            .collect::<Vec<_>>();
 2420        async move {
 2421            for future in futures {
 2422                future.await;
 2423            }
 2424        }
 2425    }
 2426
 2427    pub fn close_global(cx: &mut App) {
 2428        cx.defer(|cx| {
 2429            cx.windows().iter().find(|window| {
 2430                window
 2431                    .update(cx, |_, window, _| {
 2432                        if window.is_window_active() {
 2433                            //This can only get called when the window's project connection has been lost
 2434                            //so we don't need to prompt the user for anything and instead just close the window
 2435                            window.remove_window();
 2436                            true
 2437                        } else {
 2438                            false
 2439                        }
 2440                    })
 2441                    .unwrap_or(false)
 2442            });
 2443        });
 2444    }
 2445
 2446    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2447        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2448        cx.spawn_in(window, async move |_, cx| {
 2449            if prepare.await? {
 2450                cx.update(|window, _cx| window.remove_window())?;
 2451            }
 2452            anyhow::Ok(())
 2453        })
 2454        .detach_and_log_err(cx)
 2455    }
 2456
 2457    pub fn move_focused_panel_to_next_position(
 2458        &mut self,
 2459        _: &MoveFocusedPanelToNextPosition,
 2460        window: &mut Window,
 2461        cx: &mut Context<Self>,
 2462    ) {
 2463        let docks = self.all_docks();
 2464        let active_dock = docks
 2465            .into_iter()
 2466            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2467
 2468        if let Some(dock) = active_dock {
 2469            dock.update(cx, |dock, cx| {
 2470                let active_panel = dock
 2471                    .active_panel()
 2472                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2473
 2474                if let Some(panel) = active_panel {
 2475                    panel.move_to_next_position(window, cx);
 2476                }
 2477            })
 2478        }
 2479    }
 2480
 2481    pub fn prepare_to_close(
 2482        &mut self,
 2483        close_intent: CloseIntent,
 2484        window: &mut Window,
 2485        cx: &mut Context<Self>,
 2486    ) -> Task<Result<bool>> {
 2487        let active_call = self.active_call().cloned();
 2488
 2489        cx.spawn_in(window, async move |this, cx| {
 2490            this.update(cx, |this, _| {
 2491                if close_intent == CloseIntent::CloseWindow {
 2492                    this.removing = true;
 2493                }
 2494            })?;
 2495
 2496            let workspace_count = cx.update(|_window, cx| {
 2497                cx.windows()
 2498                    .iter()
 2499                    .filter(|window| window.downcast::<Workspace>().is_some())
 2500                    .count()
 2501            })?;
 2502
 2503            #[cfg(target_os = "macos")]
 2504            let save_last_workspace = false;
 2505
 2506            // On Linux and Windows, closing the last window should restore the last workspace.
 2507            #[cfg(not(target_os = "macos"))]
 2508            let save_last_workspace = {
 2509                let remaining_workspaces = cx.update(|_window, cx| {
 2510                    cx.windows()
 2511                        .iter()
 2512                        .filter_map(|window| window.downcast::<Workspace>())
 2513                        .filter_map(|workspace| {
 2514                            workspace
 2515                                .update(cx, |workspace, _, _| workspace.removing)
 2516                                .ok()
 2517                        })
 2518                        .filter(|removing| !removing)
 2519                        .count()
 2520                })?;
 2521
 2522                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2523            };
 2524
 2525            if let Some(active_call) = active_call
 2526                && workspace_count == 1
 2527                && active_call.read_with(cx, |call, _| call.room().is_some())?
 2528            {
 2529                if close_intent == CloseIntent::CloseWindow {
 2530                    let answer = cx.update(|window, cx| {
 2531                        window.prompt(
 2532                            PromptLevel::Warning,
 2533                            "Do you want to leave the current call?",
 2534                            None,
 2535                            &["Close window and hang up", "Cancel"],
 2536                            cx,
 2537                        )
 2538                    })?;
 2539
 2540                    if answer.await.log_err() == Some(1) {
 2541                        return anyhow::Ok(false);
 2542                    } else {
 2543                        active_call
 2544                            .update(cx, |call, cx| call.hang_up(cx))?
 2545                            .await
 2546                            .log_err();
 2547                    }
 2548                }
 2549                if close_intent == CloseIntent::ReplaceWindow {
 2550                    _ = active_call.update(cx, |this, cx| {
 2551                        let workspace = cx
 2552                            .windows()
 2553                            .iter()
 2554                            .filter_map(|window| window.downcast::<Workspace>())
 2555                            .next()
 2556                            .unwrap();
 2557                        let project = workspace.read(cx)?.project.clone();
 2558                        if project.read(cx).is_shared() {
 2559                            this.unshare_project(project, cx)?;
 2560                        }
 2561                        Ok::<_, anyhow::Error>(())
 2562                    })?;
 2563                }
 2564            }
 2565
 2566            let save_result = this
 2567                .update_in(cx, |this, window, cx| {
 2568                    this.save_all_internal(SaveIntent::Close, window, cx)
 2569                })?
 2570                .await;
 2571
 2572            // If we're not quitting, but closing, we remove the workspace from
 2573            // the current session.
 2574            if close_intent != CloseIntent::Quit
 2575                && !save_last_workspace
 2576                && save_result.as_ref().is_ok_and(|&res| res)
 2577            {
 2578                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2579                    .await;
 2580            }
 2581
 2582            save_result
 2583        })
 2584    }
 2585
 2586    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2587        self.save_all_internal(
 2588            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2589            window,
 2590            cx,
 2591        )
 2592        .detach_and_log_err(cx);
 2593    }
 2594
 2595    fn send_keystrokes(
 2596        &mut self,
 2597        action: &SendKeystrokes,
 2598        window: &mut Window,
 2599        cx: &mut Context<Self>,
 2600    ) {
 2601        let keystrokes: Vec<Keystroke> = action
 2602            .0
 2603            .split(' ')
 2604            .flat_map(|k| Keystroke::parse(k).log_err())
 2605            .map(|k| {
 2606                cx.keyboard_mapper()
 2607                    .map_key_equivalent(k, true)
 2608                    .inner()
 2609                    .clone()
 2610            })
 2611            .collect();
 2612        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2613    }
 2614
 2615    pub fn send_keystrokes_impl(
 2616        &mut self,
 2617        keystrokes: Vec<Keystroke>,
 2618        window: &mut Window,
 2619        cx: &mut Context<Self>,
 2620    ) -> Shared<Task<()>> {
 2621        let mut state = self.dispatching_keystrokes.borrow_mut();
 2622        if !state.dispatched.insert(keystrokes.clone()) {
 2623            cx.propagate();
 2624            return state.task.clone().unwrap();
 2625        }
 2626
 2627        state.queue.extend(keystrokes);
 2628
 2629        let keystrokes = self.dispatching_keystrokes.clone();
 2630        if state.task.is_none() {
 2631            state.task = Some(
 2632                window
 2633                    .spawn(cx, async move |cx| {
 2634                        // limit to 100 keystrokes to avoid infinite recursion.
 2635                        for _ in 0..100 {
 2636                            let mut state = keystrokes.borrow_mut();
 2637                            let Some(keystroke) = state.queue.pop_front() else {
 2638                                state.dispatched.clear();
 2639                                state.task.take();
 2640                                return;
 2641                            };
 2642                            drop(state);
 2643                            cx.update(|window, cx| {
 2644                                let focused = window.focused(cx);
 2645                                window.dispatch_keystroke(keystroke.clone(), cx);
 2646                                if window.focused(cx) != focused {
 2647                                    // dispatch_keystroke may cause the focus to change.
 2648                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2649                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2650                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2651                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2652                                    // )
 2653                                    window.draw(cx).clear();
 2654                                }
 2655                            })
 2656                            .ok();
 2657                        }
 2658
 2659                        *keystrokes.borrow_mut() = Default::default();
 2660                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2661                    })
 2662                    .shared(),
 2663            );
 2664        }
 2665        state.task.clone().unwrap()
 2666    }
 2667
 2668    fn save_all_internal(
 2669        &mut self,
 2670        mut save_intent: SaveIntent,
 2671        window: &mut Window,
 2672        cx: &mut Context<Self>,
 2673    ) -> Task<Result<bool>> {
 2674        if self.project.read(cx).is_disconnected(cx) {
 2675            return Task::ready(Ok(true));
 2676        }
 2677        let dirty_items = self
 2678            .panes
 2679            .iter()
 2680            .flat_map(|pane| {
 2681                pane.read(cx).items().filter_map(|item| {
 2682                    if item.is_dirty(cx) {
 2683                        item.tab_content_text(0, cx);
 2684                        Some((pane.downgrade(), item.boxed_clone()))
 2685                    } else {
 2686                        None
 2687                    }
 2688                })
 2689            })
 2690            .collect::<Vec<_>>();
 2691
 2692        let project = self.project.clone();
 2693        cx.spawn_in(window, async move |workspace, cx| {
 2694            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2695                let (serialize_tasks, remaining_dirty_items) =
 2696                    workspace.update_in(cx, |workspace, window, cx| {
 2697                        let mut remaining_dirty_items = Vec::new();
 2698                        let mut serialize_tasks = Vec::new();
 2699                        for (pane, item) in dirty_items {
 2700                            if let Some(task) = item
 2701                                .to_serializable_item_handle(cx)
 2702                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2703                            {
 2704                                serialize_tasks.push(task);
 2705                            } else {
 2706                                remaining_dirty_items.push((pane, item));
 2707                            }
 2708                        }
 2709                        (serialize_tasks, remaining_dirty_items)
 2710                    })?;
 2711
 2712                futures::future::try_join_all(serialize_tasks).await?;
 2713
 2714                if remaining_dirty_items.len() > 1 {
 2715                    let answer = workspace.update_in(cx, |_, window, cx| {
 2716                        let detail = Pane::file_names_for_prompt(
 2717                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2718                            cx,
 2719                        );
 2720                        window.prompt(
 2721                            PromptLevel::Warning,
 2722                            "Do you want to save all changes in the following files?",
 2723                            Some(&detail),
 2724                            &["Save all", "Discard all", "Cancel"],
 2725                            cx,
 2726                        )
 2727                    })?;
 2728                    match answer.await.log_err() {
 2729                        Some(0) => save_intent = SaveIntent::SaveAll,
 2730                        Some(1) => save_intent = SaveIntent::Skip,
 2731                        Some(2) => return Ok(false),
 2732                        _ => {}
 2733                    }
 2734                }
 2735
 2736                remaining_dirty_items
 2737            } else {
 2738                dirty_items
 2739            };
 2740
 2741            for (pane, item) in dirty_items {
 2742                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2743                    (
 2744                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2745                        item.project_entry_ids(cx),
 2746                    )
 2747                })?;
 2748                if (singleton || !project_entry_ids.is_empty())
 2749                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2750                {
 2751                    return Ok(false);
 2752                }
 2753            }
 2754            Ok(true)
 2755        })
 2756    }
 2757
 2758    pub fn open_workspace_for_paths(
 2759        &mut self,
 2760        replace_current_window: bool,
 2761        paths: Vec<PathBuf>,
 2762        window: &mut Window,
 2763        cx: &mut Context<Self>,
 2764    ) -> Task<Result<()>> {
 2765        let window_handle = window.window_handle().downcast::<Self>();
 2766        let is_remote = self.project.read(cx).is_via_collab();
 2767        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2768        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2769
 2770        let window_to_replace = if replace_current_window {
 2771            window_handle
 2772        } else if is_remote || has_worktree || has_dirty_items {
 2773            None
 2774        } else {
 2775            window_handle
 2776        };
 2777        let app_state = self.app_state.clone();
 2778
 2779        cx.spawn(async move |_, cx| {
 2780            cx.update(|cx| {
 2781                open_paths(
 2782                    &paths,
 2783                    app_state,
 2784                    OpenOptions {
 2785                        replace_window: window_to_replace,
 2786                        ..Default::default()
 2787                    },
 2788                    cx,
 2789                )
 2790            })?
 2791            .await?;
 2792            Ok(())
 2793        })
 2794    }
 2795
 2796    #[allow(clippy::type_complexity)]
 2797    pub fn open_paths(
 2798        &mut self,
 2799        mut abs_paths: Vec<PathBuf>,
 2800        options: OpenOptions,
 2801        pane: Option<WeakEntity<Pane>>,
 2802        window: &mut Window,
 2803        cx: &mut Context<Self>,
 2804    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2805        let fs = self.app_state.fs.clone();
 2806
 2807        // Sort the paths to ensure we add worktrees for parents before their children.
 2808        abs_paths.sort_unstable();
 2809        cx.spawn_in(window, async move |this, cx| {
 2810            let mut tasks = Vec::with_capacity(abs_paths.len());
 2811
 2812            for abs_path in &abs_paths {
 2813                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2814                    OpenVisible::All => Some(true),
 2815                    OpenVisible::None => Some(false),
 2816                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2817                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2818                        Some(None) => Some(true),
 2819                        None => None,
 2820                    },
 2821                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2822                        Some(Some(metadata)) => Some(metadata.is_dir),
 2823                        Some(None) => Some(false),
 2824                        None => None,
 2825                    },
 2826                };
 2827                let project_path = match visible {
 2828                    Some(visible) => match this
 2829                        .update(cx, |this, cx| {
 2830                            Workspace::project_path_for_path(
 2831                                this.project.clone(),
 2832                                abs_path,
 2833                                visible,
 2834                                cx,
 2835                            )
 2836                        })
 2837                        .log_err()
 2838                    {
 2839                        Some(project_path) => project_path.await.log_err(),
 2840                        None => None,
 2841                    },
 2842                    None => None,
 2843                };
 2844
 2845                let this = this.clone();
 2846                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 2847                let fs = fs.clone();
 2848                let pane = pane.clone();
 2849                let task = cx.spawn(async move |cx| {
 2850                    let (worktree, project_path) = project_path?;
 2851                    if fs.is_dir(&abs_path).await {
 2852                        this.update(cx, |workspace, cx| {
 2853                            let worktree = worktree.read(cx);
 2854                            let worktree_abs_path = worktree.abs_path();
 2855                            let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
 2856                                worktree.root_entry()
 2857                            } else {
 2858                                abs_path
 2859                                    .strip_prefix(worktree_abs_path.as_ref())
 2860                                    .ok()
 2861                                    .and_then(|relative_path| {
 2862                                        let relative_path =
 2863                                            RelPath::new(relative_path, PathStyle::local())
 2864                                                .log_err()?;
 2865                                        worktree.entry_for_path(&relative_path)
 2866                                    })
 2867                            }
 2868                            .map(|entry| entry.id);
 2869                            if let Some(entry_id) = entry_id {
 2870                                workspace.project.update(cx, |_, cx| {
 2871                                    cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 2872                                })
 2873                            }
 2874                        })
 2875                        .ok()?;
 2876                        None
 2877                    } else {
 2878                        Some(
 2879                            this.update_in(cx, |this, window, cx| {
 2880                                this.open_path(
 2881                                    project_path,
 2882                                    pane,
 2883                                    options.focus.unwrap_or(true),
 2884                                    window,
 2885                                    cx,
 2886                                )
 2887                            })
 2888                            .ok()?
 2889                            .await,
 2890                        )
 2891                    }
 2892                });
 2893                tasks.push(task);
 2894            }
 2895
 2896            futures::future::join_all(tasks).await
 2897        })
 2898    }
 2899
 2900    pub fn open_resolved_path(
 2901        &mut self,
 2902        path: ResolvedPath,
 2903        window: &mut Window,
 2904        cx: &mut Context<Self>,
 2905    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 2906        match path {
 2907            ResolvedPath::ProjectPath { project_path, .. } => {
 2908                self.open_path(project_path, None, true, window, cx)
 2909            }
 2910            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 2911                PathBuf::from(path),
 2912                OpenOptions {
 2913                    visible: Some(OpenVisible::None),
 2914                    ..Default::default()
 2915                },
 2916                window,
 2917                cx,
 2918            ),
 2919        }
 2920    }
 2921
 2922    pub fn absolute_path_of_worktree(
 2923        &self,
 2924        worktree_id: WorktreeId,
 2925        cx: &mut Context<Self>,
 2926    ) -> Option<PathBuf> {
 2927        self.project
 2928            .read(cx)
 2929            .worktree_for_id(worktree_id, cx)
 2930            // TODO: use `abs_path` or `root_dir`
 2931            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 2932    }
 2933
 2934    fn add_folder_to_project(
 2935        &mut self,
 2936        _: &AddFolderToProject,
 2937        window: &mut Window,
 2938        cx: &mut Context<Self>,
 2939    ) {
 2940        let project = self.project.read(cx);
 2941        if project.is_via_collab() {
 2942            self.show_error(
 2943                &anyhow!("You cannot add folders to someone else's project"),
 2944                cx,
 2945            );
 2946            return;
 2947        }
 2948        let paths = self.prompt_for_open_path(
 2949            PathPromptOptions {
 2950                files: false,
 2951                directories: true,
 2952                multiple: true,
 2953                prompt: None,
 2954            },
 2955            DirectoryLister::Project(self.project.clone()),
 2956            window,
 2957            cx,
 2958        );
 2959        cx.spawn_in(window, async move |this, cx| {
 2960            if let Some(paths) = paths.await.log_err().flatten() {
 2961                let results = this
 2962                    .update_in(cx, |this, window, cx| {
 2963                        this.open_paths(
 2964                            paths,
 2965                            OpenOptions {
 2966                                visible: Some(OpenVisible::All),
 2967                                ..Default::default()
 2968                            },
 2969                            None,
 2970                            window,
 2971                            cx,
 2972                        )
 2973                    })?
 2974                    .await;
 2975                for result in results.into_iter().flatten() {
 2976                    result.log_err();
 2977                }
 2978            }
 2979            anyhow::Ok(())
 2980        })
 2981        .detach_and_log_err(cx);
 2982    }
 2983
 2984    pub fn project_path_for_path(
 2985        project: Entity<Project>,
 2986        abs_path: &Path,
 2987        visible: bool,
 2988        cx: &mut App,
 2989    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 2990        let entry = project.update(cx, |project, cx| {
 2991            project.find_or_create_worktree(abs_path, visible, cx)
 2992        });
 2993        cx.spawn(async move |cx| {
 2994            let (worktree, path) = entry.await?;
 2995            let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
 2996            Ok((
 2997                worktree,
 2998                ProjectPath {
 2999                    worktree_id,
 3000                    path: path,
 3001                },
 3002            ))
 3003        })
 3004    }
 3005
 3006    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3007        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3008    }
 3009
 3010    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3011        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3012    }
 3013
 3014    pub fn items_of_type<'a, T: Item>(
 3015        &'a self,
 3016        cx: &'a App,
 3017    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3018        self.panes
 3019            .iter()
 3020            .flat_map(|pane| pane.read(cx).items_of_type())
 3021    }
 3022
 3023    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3024        self.active_pane().read(cx).active_item()
 3025    }
 3026
 3027    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3028        let item = self.active_item(cx)?;
 3029        item.to_any_view().downcast::<I>().ok()
 3030    }
 3031
 3032    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3033        self.active_item(cx).and_then(|item| item.project_path(cx))
 3034    }
 3035
 3036    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3037        self.recent_navigation_history_iter(cx)
 3038            .filter_map(|(path, abs_path)| {
 3039                let worktree = self
 3040                    .project
 3041                    .read(cx)
 3042                    .worktree_for_id(path.worktree_id, cx)?;
 3043                if worktree.read(cx).is_visible() {
 3044                    abs_path
 3045                } else {
 3046                    None
 3047                }
 3048            })
 3049            .next()
 3050    }
 3051
 3052    pub fn save_active_item(
 3053        &mut self,
 3054        save_intent: SaveIntent,
 3055        window: &mut Window,
 3056        cx: &mut App,
 3057    ) -> Task<Result<()>> {
 3058        let project = self.project.clone();
 3059        let pane = self.active_pane();
 3060        let item = pane.read(cx).active_item();
 3061        let pane = pane.downgrade();
 3062
 3063        window.spawn(cx, async move |cx| {
 3064            if let Some(item) = item {
 3065                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3066                    .await
 3067                    .map(|_| ())
 3068            } else {
 3069                Ok(())
 3070            }
 3071        })
 3072    }
 3073
 3074    pub fn close_inactive_items_and_panes(
 3075        &mut self,
 3076        action: &CloseInactiveTabsAndPanes,
 3077        window: &mut Window,
 3078        cx: &mut Context<Self>,
 3079    ) {
 3080        if let Some(task) = self.close_all_internal(
 3081            true,
 3082            action.save_intent.unwrap_or(SaveIntent::Close),
 3083            window,
 3084            cx,
 3085        ) {
 3086            task.detach_and_log_err(cx)
 3087        }
 3088    }
 3089
 3090    pub fn close_all_items_and_panes(
 3091        &mut self,
 3092        action: &CloseAllItemsAndPanes,
 3093        window: &mut Window,
 3094        cx: &mut Context<Self>,
 3095    ) {
 3096        if let Some(task) = self.close_all_internal(
 3097            false,
 3098            action.save_intent.unwrap_or(SaveIntent::Close),
 3099            window,
 3100            cx,
 3101        ) {
 3102            task.detach_and_log_err(cx)
 3103        }
 3104    }
 3105
 3106    fn close_all_internal(
 3107        &mut self,
 3108        retain_active_pane: bool,
 3109        save_intent: SaveIntent,
 3110        window: &mut Window,
 3111        cx: &mut Context<Self>,
 3112    ) -> Option<Task<Result<()>>> {
 3113        let current_pane = self.active_pane();
 3114
 3115        let mut tasks = Vec::new();
 3116
 3117        if retain_active_pane {
 3118            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3119                pane.close_other_items(
 3120                    &CloseOtherItems {
 3121                        save_intent: None,
 3122                        close_pinned: false,
 3123                    },
 3124                    None,
 3125                    window,
 3126                    cx,
 3127                )
 3128            });
 3129
 3130            tasks.push(current_pane_close);
 3131        }
 3132
 3133        for pane in self.panes() {
 3134            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3135                continue;
 3136            }
 3137
 3138            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3139                pane.close_all_items(
 3140                    &CloseAllItems {
 3141                        save_intent: Some(save_intent),
 3142                        close_pinned: false,
 3143                    },
 3144                    window,
 3145                    cx,
 3146                )
 3147            });
 3148
 3149            tasks.push(close_pane_items)
 3150        }
 3151
 3152        if tasks.is_empty() {
 3153            None
 3154        } else {
 3155            Some(cx.spawn_in(window, async move |_, _| {
 3156                for task in tasks {
 3157                    task.await?
 3158                }
 3159                Ok(())
 3160            }))
 3161        }
 3162    }
 3163
 3164    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3165        self.dock_at_position(position).read(cx).is_open()
 3166    }
 3167
 3168    pub fn toggle_dock(
 3169        &mut self,
 3170        dock_side: DockPosition,
 3171        window: &mut Window,
 3172        cx: &mut Context<Self>,
 3173    ) {
 3174        let mut focus_center = false;
 3175        let mut reveal_dock = false;
 3176
 3177        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3178        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3179        if was_visible {
 3180            self.save_open_dock_positions(cx);
 3181        }
 3182
 3183        let dock = self.dock_at_position(dock_side);
 3184        dock.update(cx, |dock, cx| {
 3185            dock.set_open(!was_visible, window, cx);
 3186
 3187            if dock.active_panel().is_none() {
 3188                let Some(panel_ix) = dock
 3189                    .first_enabled_panel_idx(cx)
 3190                    .log_with_level(log::Level::Info)
 3191                else {
 3192                    return;
 3193                };
 3194                dock.activate_panel(panel_ix, window, cx);
 3195            }
 3196
 3197            if let Some(active_panel) = dock.active_panel() {
 3198                if was_visible {
 3199                    if active_panel
 3200                        .panel_focus_handle(cx)
 3201                        .contains_focused(window, cx)
 3202                    {
 3203                        focus_center = true;
 3204                    }
 3205                } else {
 3206                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3207                    window.focus(focus_handle, cx);
 3208                    reveal_dock = true;
 3209                }
 3210            }
 3211        });
 3212
 3213        if reveal_dock {
 3214            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3215        }
 3216
 3217        if focus_center {
 3218            self.active_pane
 3219                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3220        }
 3221
 3222        cx.notify();
 3223        self.serialize_workspace(window, cx);
 3224    }
 3225
 3226    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3227        self.all_docks().into_iter().find(|&dock| {
 3228            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3229        })
 3230    }
 3231
 3232    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3233        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3234            self.save_open_dock_positions(cx);
 3235            dock.update(cx, |dock, cx| {
 3236                dock.set_open(false, window, cx);
 3237            });
 3238            return true;
 3239        }
 3240        false
 3241    }
 3242
 3243    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3244        self.save_open_dock_positions(cx);
 3245        for dock in self.all_docks() {
 3246            dock.update(cx, |dock, cx| {
 3247                dock.set_open(false, window, cx);
 3248            });
 3249        }
 3250
 3251        cx.focus_self(window);
 3252        cx.notify();
 3253        self.serialize_workspace(window, cx);
 3254    }
 3255
 3256    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3257        self.all_docks()
 3258            .into_iter()
 3259            .filter_map(|dock| {
 3260                let dock_ref = dock.read(cx);
 3261                if dock_ref.is_open() {
 3262                    Some(dock_ref.position())
 3263                } else {
 3264                    None
 3265                }
 3266            })
 3267            .collect()
 3268    }
 3269
 3270    /// Saves the positions of currently open docks.
 3271    ///
 3272    /// Updates `last_open_dock_positions` with positions of all currently open
 3273    /// docks, to later be restored by the 'Toggle All Docks' action.
 3274    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3275        let open_dock_positions = self.get_open_dock_positions(cx);
 3276        if !open_dock_positions.is_empty() {
 3277            self.last_open_dock_positions = open_dock_positions;
 3278        }
 3279    }
 3280
 3281    /// Toggles all docks between open and closed states.
 3282    ///
 3283    /// If any docks are open, closes all and remembers their positions. If all
 3284    /// docks are closed, restores the last remembered dock configuration.
 3285    fn toggle_all_docks(
 3286        &mut self,
 3287        _: &ToggleAllDocks,
 3288        window: &mut Window,
 3289        cx: &mut Context<Self>,
 3290    ) {
 3291        let open_dock_positions = self.get_open_dock_positions(cx);
 3292
 3293        if !open_dock_positions.is_empty() {
 3294            self.close_all_docks(window, cx);
 3295        } else if !self.last_open_dock_positions.is_empty() {
 3296            self.restore_last_open_docks(window, cx);
 3297        }
 3298    }
 3299
 3300    /// Reopens docks from the most recently remembered configuration.
 3301    ///
 3302    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3303    /// and clears the stored positions.
 3304    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3305        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3306
 3307        for position in positions_to_open {
 3308            let dock = self.dock_at_position(position);
 3309            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3310        }
 3311
 3312        cx.focus_self(window);
 3313        cx.notify();
 3314        self.serialize_workspace(window, cx);
 3315    }
 3316
 3317    /// Transfer focus to the panel of the given type.
 3318    pub fn focus_panel<T: Panel>(
 3319        &mut self,
 3320        window: &mut Window,
 3321        cx: &mut Context<Self>,
 3322    ) -> Option<Entity<T>> {
 3323        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 3324        panel.to_any().downcast().ok()
 3325    }
 3326
 3327    /// Focus the panel of the given type if it isn't already focused. If it is
 3328    /// already focused, then transfer focus back to the workspace center.
 3329    pub fn toggle_panel_focus<T: Panel>(
 3330        &mut self,
 3331        window: &mut Window,
 3332        cx: &mut Context<Self>,
 3333    ) -> bool {
 3334        let mut did_focus_panel = false;
 3335        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3336            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3337            did_focus_panel
 3338        });
 3339        did_focus_panel
 3340    }
 3341
 3342    pub fn activate_panel_for_proto_id(
 3343        &mut self,
 3344        panel_id: PanelId,
 3345        window: &mut Window,
 3346        cx: &mut Context<Self>,
 3347    ) -> Option<Arc<dyn PanelHandle>> {
 3348        let mut panel = None;
 3349        for dock in self.all_docks() {
 3350            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3351                panel = dock.update(cx, |dock, cx| {
 3352                    dock.activate_panel(panel_index, window, cx);
 3353                    dock.set_open(true, window, cx);
 3354                    dock.active_panel().cloned()
 3355                });
 3356                break;
 3357            }
 3358        }
 3359
 3360        if panel.is_some() {
 3361            cx.notify();
 3362            self.serialize_workspace(window, cx);
 3363        }
 3364
 3365        panel
 3366    }
 3367
 3368    /// Focus or unfocus the given panel type, depending on the given callback.
 3369    fn focus_or_unfocus_panel<T: Panel>(
 3370        &mut self,
 3371        window: &mut Window,
 3372        cx: &mut Context<Self>,
 3373        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3374    ) -> Option<Arc<dyn PanelHandle>> {
 3375        let mut result_panel = None;
 3376        let mut serialize = false;
 3377        for dock in self.all_docks() {
 3378            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3379                let mut focus_center = false;
 3380                let panel = dock.update(cx, |dock, cx| {
 3381                    dock.activate_panel(panel_index, window, cx);
 3382
 3383                    let panel = dock.active_panel().cloned();
 3384                    if let Some(panel) = panel.as_ref() {
 3385                        if should_focus(&**panel, window, cx) {
 3386                            dock.set_open(true, window, cx);
 3387                            panel.panel_focus_handle(cx).focus(window, cx);
 3388                        } else {
 3389                            focus_center = true;
 3390                        }
 3391                    }
 3392                    panel
 3393                });
 3394
 3395                if focus_center {
 3396                    self.active_pane
 3397                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3398                }
 3399
 3400                result_panel = panel;
 3401                serialize = true;
 3402                break;
 3403            }
 3404        }
 3405
 3406        if serialize {
 3407            self.serialize_workspace(window, cx);
 3408        }
 3409
 3410        cx.notify();
 3411        result_panel
 3412    }
 3413
 3414    /// Open the panel of the given type
 3415    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3416        for dock in self.all_docks() {
 3417            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3418                dock.update(cx, |dock, cx| {
 3419                    dock.activate_panel(panel_index, window, cx);
 3420                    dock.set_open(true, window, cx);
 3421                });
 3422            }
 3423        }
 3424    }
 3425
 3426    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3427        for dock in self.all_docks().iter() {
 3428            dock.update(cx, |dock, cx| {
 3429                if dock.panel::<T>().is_some() {
 3430                    dock.set_open(false, window, cx)
 3431                }
 3432            })
 3433        }
 3434    }
 3435
 3436    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3437        self.all_docks()
 3438            .iter()
 3439            .find_map(|dock| dock.read(cx).panel::<T>())
 3440    }
 3441
 3442    fn dismiss_zoomed_items_to_reveal(
 3443        &mut self,
 3444        dock_to_reveal: Option<DockPosition>,
 3445        window: &mut Window,
 3446        cx: &mut Context<Self>,
 3447    ) {
 3448        // If a center pane is zoomed, unzoom it.
 3449        for pane in &self.panes {
 3450            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3451                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3452            }
 3453        }
 3454
 3455        // If another dock is zoomed, hide it.
 3456        let mut focus_center = false;
 3457        for dock in self.all_docks() {
 3458            dock.update(cx, |dock, cx| {
 3459                if Some(dock.position()) != dock_to_reveal
 3460                    && let Some(panel) = dock.active_panel()
 3461                    && panel.is_zoomed(window, cx)
 3462                {
 3463                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3464                    dock.set_open(false, window, cx);
 3465                }
 3466            });
 3467        }
 3468
 3469        if focus_center {
 3470            self.active_pane
 3471                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3472        }
 3473
 3474        if self.zoomed_position != dock_to_reveal {
 3475            self.zoomed = None;
 3476            self.zoomed_position = None;
 3477            cx.emit(Event::ZoomChanged);
 3478        }
 3479
 3480        cx.notify();
 3481    }
 3482
 3483    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3484        let pane = cx.new(|cx| {
 3485            let mut pane = Pane::new(
 3486                self.weak_handle(),
 3487                self.project.clone(),
 3488                self.pane_history_timestamp.clone(),
 3489                None,
 3490                NewFile.boxed_clone(),
 3491                true,
 3492                window,
 3493                cx,
 3494            );
 3495            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3496            pane
 3497        });
 3498        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3499            .detach();
 3500        self.panes.push(pane.clone());
 3501
 3502        window.focus(&pane.focus_handle(cx), cx);
 3503
 3504        cx.emit(Event::PaneAdded(pane.clone()));
 3505        pane
 3506    }
 3507
 3508    pub fn add_item_to_center(
 3509        &mut self,
 3510        item: Box<dyn ItemHandle>,
 3511        window: &mut Window,
 3512        cx: &mut Context<Self>,
 3513    ) -> bool {
 3514        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3515            if let Some(center_pane) = center_pane.upgrade() {
 3516                center_pane.update(cx, |pane, cx| {
 3517                    pane.add_item(item, true, true, None, window, cx)
 3518                });
 3519                true
 3520            } else {
 3521                false
 3522            }
 3523        } else {
 3524            false
 3525        }
 3526    }
 3527
 3528    pub fn add_item_to_active_pane(
 3529        &mut self,
 3530        item: Box<dyn ItemHandle>,
 3531        destination_index: Option<usize>,
 3532        focus_item: bool,
 3533        window: &mut Window,
 3534        cx: &mut App,
 3535    ) {
 3536        self.add_item(
 3537            self.active_pane.clone(),
 3538            item,
 3539            destination_index,
 3540            false,
 3541            focus_item,
 3542            window,
 3543            cx,
 3544        )
 3545    }
 3546
 3547    pub fn add_item(
 3548        &mut self,
 3549        pane: Entity<Pane>,
 3550        item: Box<dyn ItemHandle>,
 3551        destination_index: Option<usize>,
 3552        activate_pane: bool,
 3553        focus_item: bool,
 3554        window: &mut Window,
 3555        cx: &mut App,
 3556    ) {
 3557        pane.update(cx, |pane, cx| {
 3558            pane.add_item(
 3559                item,
 3560                activate_pane,
 3561                focus_item,
 3562                destination_index,
 3563                window,
 3564                cx,
 3565            )
 3566        });
 3567    }
 3568
 3569    pub fn split_item(
 3570        &mut self,
 3571        split_direction: SplitDirection,
 3572        item: Box<dyn ItemHandle>,
 3573        window: &mut Window,
 3574        cx: &mut Context<Self>,
 3575    ) {
 3576        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3577        self.add_item(new_pane, item, None, true, true, window, cx);
 3578    }
 3579
 3580    pub fn open_abs_path(
 3581        &mut self,
 3582        abs_path: PathBuf,
 3583        options: OpenOptions,
 3584        window: &mut Window,
 3585        cx: &mut Context<Self>,
 3586    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3587        cx.spawn_in(window, async move |workspace, cx| {
 3588            let open_paths_task_result = workspace
 3589                .update_in(cx, |workspace, window, cx| {
 3590                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3591                })
 3592                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3593                .await;
 3594            anyhow::ensure!(
 3595                open_paths_task_result.len() == 1,
 3596                "open abs path {abs_path:?} task returned incorrect number of results"
 3597            );
 3598            match open_paths_task_result
 3599                .into_iter()
 3600                .next()
 3601                .expect("ensured single task result")
 3602            {
 3603                Some(open_result) => {
 3604                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3605                }
 3606                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3607            }
 3608        })
 3609    }
 3610
 3611    pub fn split_abs_path(
 3612        &mut self,
 3613        abs_path: PathBuf,
 3614        visible: bool,
 3615        window: &mut Window,
 3616        cx: &mut Context<Self>,
 3617    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3618        let project_path_task =
 3619            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3620        cx.spawn_in(window, async move |this, cx| {
 3621            let (_, path) = project_path_task.await?;
 3622            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3623                .await
 3624        })
 3625    }
 3626
 3627    pub fn open_path(
 3628        &mut self,
 3629        path: impl Into<ProjectPath>,
 3630        pane: Option<WeakEntity<Pane>>,
 3631        focus_item: bool,
 3632        window: &mut Window,
 3633        cx: &mut App,
 3634    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3635        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3636    }
 3637
 3638    pub fn open_path_preview(
 3639        &mut self,
 3640        path: impl Into<ProjectPath>,
 3641        pane: Option<WeakEntity<Pane>>,
 3642        focus_item: bool,
 3643        allow_preview: bool,
 3644        activate: bool,
 3645        window: &mut Window,
 3646        cx: &mut App,
 3647    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3648        let pane = pane.unwrap_or_else(|| {
 3649            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3650                self.panes
 3651                    .first()
 3652                    .expect("There must be an active pane")
 3653                    .downgrade()
 3654            })
 3655        });
 3656
 3657        let project_path = path.into();
 3658        let task = self.load_path(project_path.clone(), window, cx);
 3659        window.spawn(cx, async move |cx| {
 3660            let (project_entry_id, build_item) = task.await?;
 3661
 3662            pane.update_in(cx, |pane, window, cx| {
 3663                pane.open_item(
 3664                    project_entry_id,
 3665                    project_path,
 3666                    focus_item,
 3667                    allow_preview,
 3668                    activate,
 3669                    None,
 3670                    window,
 3671                    cx,
 3672                    build_item,
 3673                )
 3674            })
 3675        })
 3676    }
 3677
 3678    pub fn split_path(
 3679        &mut self,
 3680        path: impl Into<ProjectPath>,
 3681        window: &mut Window,
 3682        cx: &mut Context<Self>,
 3683    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3684        self.split_path_preview(path, false, None, window, cx)
 3685    }
 3686
 3687    pub fn split_path_preview(
 3688        &mut self,
 3689        path: impl Into<ProjectPath>,
 3690        allow_preview: bool,
 3691        split_direction: Option<SplitDirection>,
 3692        window: &mut Window,
 3693        cx: &mut Context<Self>,
 3694    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3695        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3696            self.panes
 3697                .first()
 3698                .expect("There must be an active pane")
 3699                .downgrade()
 3700        });
 3701
 3702        if let Member::Pane(center_pane) = &self.center.root
 3703            && center_pane.read(cx).items_len() == 0
 3704        {
 3705            return self.open_path(path, Some(pane), true, window, cx);
 3706        }
 3707
 3708        let project_path = path.into();
 3709        let task = self.load_path(project_path.clone(), window, cx);
 3710        cx.spawn_in(window, async move |this, cx| {
 3711            let (project_entry_id, build_item) = task.await?;
 3712            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3713                let pane = pane.upgrade()?;
 3714                let new_pane = this.split_pane(
 3715                    pane,
 3716                    split_direction.unwrap_or(SplitDirection::Right),
 3717                    window,
 3718                    cx,
 3719                );
 3720                new_pane.update(cx, |new_pane, cx| {
 3721                    Some(new_pane.open_item(
 3722                        project_entry_id,
 3723                        project_path,
 3724                        true,
 3725                        allow_preview,
 3726                        true,
 3727                        None,
 3728                        window,
 3729                        cx,
 3730                        build_item,
 3731                    ))
 3732                })
 3733            })
 3734            .map(|option| option.context("pane was dropped"))?
 3735        })
 3736    }
 3737
 3738    fn load_path(
 3739        &mut self,
 3740        path: ProjectPath,
 3741        window: &mut Window,
 3742        cx: &mut App,
 3743    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3744        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3745        registry.open_path(self.project(), &path, window, cx)
 3746    }
 3747
 3748    pub fn find_project_item<T>(
 3749        &self,
 3750        pane: &Entity<Pane>,
 3751        project_item: &Entity<T::Item>,
 3752        cx: &App,
 3753    ) -> Option<Entity<T>>
 3754    where
 3755        T: ProjectItem,
 3756    {
 3757        use project::ProjectItem as _;
 3758        let project_item = project_item.read(cx);
 3759        let entry_id = project_item.entry_id(cx);
 3760        let project_path = project_item.project_path(cx);
 3761
 3762        let mut item = None;
 3763        if let Some(entry_id) = entry_id {
 3764            item = pane.read(cx).item_for_entry(entry_id, cx);
 3765        }
 3766        if item.is_none()
 3767            && let Some(project_path) = project_path
 3768        {
 3769            item = pane.read(cx).item_for_path(project_path, cx);
 3770        }
 3771
 3772        item.and_then(|item| item.downcast::<T>())
 3773    }
 3774
 3775    pub fn is_project_item_open<T>(
 3776        &self,
 3777        pane: &Entity<Pane>,
 3778        project_item: &Entity<T::Item>,
 3779        cx: &App,
 3780    ) -> bool
 3781    where
 3782        T: ProjectItem,
 3783    {
 3784        self.find_project_item::<T>(pane, project_item, cx)
 3785            .is_some()
 3786    }
 3787
 3788    pub fn open_project_item<T>(
 3789        &mut self,
 3790        pane: Entity<Pane>,
 3791        project_item: Entity<T::Item>,
 3792        activate_pane: bool,
 3793        focus_item: bool,
 3794        keep_old_preview: bool,
 3795        allow_new_preview: bool,
 3796        window: &mut Window,
 3797        cx: &mut Context<Self>,
 3798    ) -> Entity<T>
 3799    where
 3800        T: ProjectItem,
 3801    {
 3802        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 3803
 3804        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3805            if !keep_old_preview
 3806                && let Some(old_id) = old_item_id
 3807                && old_id != item.item_id()
 3808            {
 3809                // switching to a different item, so unpreview old active item
 3810                pane.update(cx, |pane, _| {
 3811                    pane.unpreview_item_if_preview(old_id);
 3812                });
 3813            }
 3814
 3815            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3816            if !allow_new_preview {
 3817                pane.update(cx, |pane, _| {
 3818                    pane.unpreview_item_if_preview(item.item_id());
 3819                });
 3820            }
 3821            return item;
 3822        }
 3823
 3824        let item = pane.update(cx, |pane, cx| {
 3825            cx.new(|cx| {
 3826                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3827            })
 3828        });
 3829        let mut destination_index = None;
 3830        pane.update(cx, |pane, cx| {
 3831            if !keep_old_preview && let Some(old_id) = old_item_id {
 3832                pane.unpreview_item_if_preview(old_id);
 3833            }
 3834            if allow_new_preview {
 3835                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 3836            }
 3837        });
 3838
 3839        self.add_item(
 3840            pane,
 3841            Box::new(item.clone()),
 3842            destination_index,
 3843            activate_pane,
 3844            focus_item,
 3845            window,
 3846            cx,
 3847        );
 3848        item
 3849    }
 3850
 3851    pub fn open_shared_screen(
 3852        &mut self,
 3853        peer_id: PeerId,
 3854        window: &mut Window,
 3855        cx: &mut Context<Self>,
 3856    ) {
 3857        if let Some(shared_screen) =
 3858            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 3859        {
 3860            self.active_pane.update(cx, |pane, cx| {
 3861                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 3862            });
 3863        }
 3864    }
 3865
 3866    pub fn activate_item(
 3867        &mut self,
 3868        item: &dyn ItemHandle,
 3869        activate_pane: bool,
 3870        focus_item: bool,
 3871        window: &mut Window,
 3872        cx: &mut App,
 3873    ) -> bool {
 3874        let result = self.panes.iter().find_map(|pane| {
 3875            pane.read(cx)
 3876                .index_for_item(item)
 3877                .map(|ix| (pane.clone(), ix))
 3878        });
 3879        if let Some((pane, ix)) = result {
 3880            pane.update(cx, |pane, cx| {
 3881                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 3882            });
 3883            true
 3884        } else {
 3885            false
 3886        }
 3887    }
 3888
 3889    fn activate_pane_at_index(
 3890        &mut self,
 3891        action: &ActivatePane,
 3892        window: &mut Window,
 3893        cx: &mut Context<Self>,
 3894    ) {
 3895        let panes = self.center.panes();
 3896        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 3897            window.focus(&pane.focus_handle(cx), cx);
 3898        } else {
 3899            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 3900                .detach();
 3901        }
 3902    }
 3903
 3904    fn move_item_to_pane_at_index(
 3905        &mut self,
 3906        action: &MoveItemToPane,
 3907        window: &mut Window,
 3908        cx: &mut Context<Self>,
 3909    ) {
 3910        let panes = self.center.panes();
 3911        let destination = match panes.get(action.destination) {
 3912            Some(&destination) => destination.clone(),
 3913            None => {
 3914                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3915                    return;
 3916                }
 3917                let direction = SplitDirection::Right;
 3918                let split_off_pane = self
 3919                    .find_pane_in_direction(direction, cx)
 3920                    .unwrap_or_else(|| self.active_pane.clone());
 3921                let new_pane = self.add_pane(window, cx);
 3922                if self
 3923                    .center
 3924                    .split(&split_off_pane, &new_pane, direction, cx)
 3925                    .log_err()
 3926                    .is_none()
 3927                {
 3928                    return;
 3929                };
 3930                new_pane
 3931            }
 3932        };
 3933
 3934        if action.clone {
 3935            if self
 3936                .active_pane
 3937                .read(cx)
 3938                .active_item()
 3939                .is_some_and(|item| item.can_split(cx))
 3940            {
 3941                clone_active_item(
 3942                    self.database_id(),
 3943                    &self.active_pane,
 3944                    &destination,
 3945                    action.focus,
 3946                    window,
 3947                    cx,
 3948                );
 3949                return;
 3950            }
 3951        }
 3952        move_active_item(
 3953            &self.active_pane,
 3954            &destination,
 3955            action.focus,
 3956            true,
 3957            window,
 3958            cx,
 3959        )
 3960    }
 3961
 3962    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3963        let panes = self.center.panes();
 3964        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3965            let next_ix = (ix + 1) % panes.len();
 3966            let next_pane = panes[next_ix].clone();
 3967            window.focus(&next_pane.focus_handle(cx), cx);
 3968        }
 3969    }
 3970
 3971    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3972        let panes = self.center.panes();
 3973        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3974            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3975            let prev_pane = panes[prev_ix].clone();
 3976            window.focus(&prev_pane.focus_handle(cx), cx);
 3977        }
 3978    }
 3979
 3980    pub fn activate_pane_in_direction(
 3981        &mut self,
 3982        direction: SplitDirection,
 3983        window: &mut Window,
 3984        cx: &mut App,
 3985    ) {
 3986        use ActivateInDirectionTarget as Target;
 3987        enum Origin {
 3988            LeftDock,
 3989            RightDock,
 3990            BottomDock,
 3991            Center,
 3992        }
 3993
 3994        let origin: Origin = [
 3995            (&self.left_dock, Origin::LeftDock),
 3996            (&self.right_dock, Origin::RightDock),
 3997            (&self.bottom_dock, Origin::BottomDock),
 3998        ]
 3999        .into_iter()
 4000        .find_map(|(dock, origin)| {
 4001            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4002                Some(origin)
 4003            } else {
 4004                None
 4005            }
 4006        })
 4007        .unwrap_or(Origin::Center);
 4008
 4009        let get_last_active_pane = || {
 4010            let pane = self
 4011                .last_active_center_pane
 4012                .clone()
 4013                .unwrap_or_else(|| {
 4014                    self.panes
 4015                        .first()
 4016                        .expect("There must be an active pane")
 4017                        .downgrade()
 4018                })
 4019                .upgrade()?;
 4020            (pane.read(cx).items_len() != 0).then_some(pane)
 4021        };
 4022
 4023        let try_dock =
 4024            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4025
 4026        let target = match (origin, direction) {
 4027            // We're in the center, so we first try to go to a different pane,
 4028            // otherwise try to go to a dock.
 4029            (Origin::Center, direction) => {
 4030                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4031                    Some(Target::Pane(pane))
 4032                } else {
 4033                    match direction {
 4034                        SplitDirection::Up => None,
 4035                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4036                        SplitDirection::Left => try_dock(&self.left_dock),
 4037                        SplitDirection::Right => try_dock(&self.right_dock),
 4038                    }
 4039                }
 4040            }
 4041
 4042            (Origin::LeftDock, SplitDirection::Right) => {
 4043                if let Some(last_active_pane) = get_last_active_pane() {
 4044                    Some(Target::Pane(last_active_pane))
 4045                } else {
 4046                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4047                }
 4048            }
 4049
 4050            (Origin::LeftDock, SplitDirection::Down)
 4051            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4052
 4053            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4054            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4055            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4056
 4057            (Origin::RightDock, SplitDirection::Left) => {
 4058                if let Some(last_active_pane) = get_last_active_pane() {
 4059                    Some(Target::Pane(last_active_pane))
 4060                } else {
 4061                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4062                }
 4063            }
 4064
 4065            _ => None,
 4066        };
 4067
 4068        match target {
 4069            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4070                let pane = pane.read(cx);
 4071                if let Some(item) = pane.active_item() {
 4072                    item.item_focus_handle(cx).focus(window, cx);
 4073                } else {
 4074                    log::error!(
 4075                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4076                    );
 4077                }
 4078            }
 4079            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4080                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4081                window.defer(cx, move |window, cx| {
 4082                    let dock = dock.read(cx);
 4083                    if let Some(panel) = dock.active_panel() {
 4084                        panel.panel_focus_handle(cx).focus(window, cx);
 4085                    } else {
 4086                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4087                    }
 4088                })
 4089            }
 4090            None => {}
 4091        }
 4092    }
 4093
 4094    pub fn move_item_to_pane_in_direction(
 4095        &mut self,
 4096        action: &MoveItemToPaneInDirection,
 4097        window: &mut Window,
 4098        cx: &mut Context<Self>,
 4099    ) {
 4100        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4101            Some(destination) => destination,
 4102            None => {
 4103                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4104                    return;
 4105                }
 4106                let new_pane = self.add_pane(window, cx);
 4107                if self
 4108                    .center
 4109                    .split(&self.active_pane, &new_pane, action.direction, cx)
 4110                    .log_err()
 4111                    .is_none()
 4112                {
 4113                    return;
 4114                };
 4115                new_pane
 4116            }
 4117        };
 4118
 4119        if action.clone {
 4120            if self
 4121                .active_pane
 4122                .read(cx)
 4123                .active_item()
 4124                .is_some_and(|item| item.can_split(cx))
 4125            {
 4126                clone_active_item(
 4127                    self.database_id(),
 4128                    &self.active_pane,
 4129                    &destination,
 4130                    action.focus,
 4131                    window,
 4132                    cx,
 4133                );
 4134                return;
 4135            }
 4136        }
 4137        move_active_item(
 4138            &self.active_pane,
 4139            &destination,
 4140            action.focus,
 4141            true,
 4142            window,
 4143            cx,
 4144        );
 4145    }
 4146
 4147    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4148        self.center.bounding_box_for_pane(pane)
 4149    }
 4150
 4151    pub fn find_pane_in_direction(
 4152        &mut self,
 4153        direction: SplitDirection,
 4154        cx: &App,
 4155    ) -> Option<Entity<Pane>> {
 4156        self.center
 4157            .find_pane_in_direction(&self.active_pane, direction, cx)
 4158            .cloned()
 4159    }
 4160
 4161    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4162        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4163            self.center.swap(&self.active_pane, &to, cx);
 4164            cx.notify();
 4165        }
 4166    }
 4167
 4168    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4169        if self
 4170            .center
 4171            .move_to_border(&self.active_pane, direction, cx)
 4172            .unwrap()
 4173        {
 4174            cx.notify();
 4175        }
 4176    }
 4177
 4178    pub fn resize_pane(
 4179        &mut self,
 4180        axis: gpui::Axis,
 4181        amount: Pixels,
 4182        window: &mut Window,
 4183        cx: &mut Context<Self>,
 4184    ) {
 4185        let docks = self.all_docks();
 4186        let active_dock = docks
 4187            .into_iter()
 4188            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4189
 4190        if let Some(dock) = active_dock {
 4191            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4192                return;
 4193            };
 4194            match dock.read(cx).position() {
 4195                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4196                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4197                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4198            }
 4199        } else {
 4200            self.center
 4201                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4202        }
 4203        cx.notify();
 4204    }
 4205
 4206    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4207        self.center.reset_pane_sizes(cx);
 4208        cx.notify();
 4209    }
 4210
 4211    fn handle_pane_focused(
 4212        &mut self,
 4213        pane: Entity<Pane>,
 4214        window: &mut Window,
 4215        cx: &mut Context<Self>,
 4216    ) {
 4217        // This is explicitly hoisted out of the following check for pane identity as
 4218        // terminal panel panes are not registered as a center panes.
 4219        self.status_bar.update(cx, |status_bar, cx| {
 4220            status_bar.set_active_pane(&pane, window, cx);
 4221        });
 4222        if self.active_pane != pane {
 4223            self.set_active_pane(&pane, window, cx);
 4224        }
 4225
 4226        if self.last_active_center_pane.is_none() {
 4227            self.last_active_center_pane = Some(pane.downgrade());
 4228        }
 4229
 4230        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 4231        if pane.read(cx).is_zoomed() {
 4232            self.zoomed = Some(pane.downgrade().into());
 4233        } else {
 4234            self.zoomed = None;
 4235        }
 4236        self.zoomed_position = None;
 4237        cx.emit(Event::ZoomChanged);
 4238        self.update_active_view_for_followers(window, cx);
 4239        pane.update(cx, |pane, _| {
 4240            pane.track_alternate_file_items();
 4241        });
 4242
 4243        cx.notify();
 4244    }
 4245
 4246    fn set_active_pane(
 4247        &mut self,
 4248        pane: &Entity<Pane>,
 4249        window: &mut Window,
 4250        cx: &mut Context<Self>,
 4251    ) {
 4252        self.active_pane = pane.clone();
 4253        self.active_item_path_changed(true, window, cx);
 4254        self.last_active_center_pane = Some(pane.downgrade());
 4255    }
 4256
 4257    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4258        self.update_active_view_for_followers(window, cx);
 4259    }
 4260
 4261    fn handle_pane_event(
 4262        &mut self,
 4263        pane: &Entity<Pane>,
 4264        event: &pane::Event,
 4265        window: &mut Window,
 4266        cx: &mut Context<Self>,
 4267    ) {
 4268        let mut serialize_workspace = true;
 4269        match event {
 4270            pane::Event::AddItem { item } => {
 4271                item.added_to_pane(self, pane.clone(), window, cx);
 4272                cx.emit(Event::ItemAdded {
 4273                    item: item.boxed_clone(),
 4274                });
 4275            }
 4276            pane::Event::Split { direction, mode } => {
 4277                match mode {
 4278                    SplitMode::ClonePane => {
 4279                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4280                            .detach();
 4281                    }
 4282                    SplitMode::EmptyPane => {
 4283                        self.split_pane(pane.clone(), *direction, window, cx);
 4284                    }
 4285                    SplitMode::MovePane => {
 4286                        self.split_and_move(pane.clone(), *direction, window, cx);
 4287                    }
 4288                };
 4289            }
 4290            pane::Event::JoinIntoNext => {
 4291                self.join_pane_into_next(pane.clone(), window, cx);
 4292            }
 4293            pane::Event::JoinAll => {
 4294                self.join_all_panes(window, cx);
 4295            }
 4296            pane::Event::Remove { focus_on_pane } => {
 4297                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4298            }
 4299            pane::Event::ActivateItem {
 4300                local,
 4301                focus_changed,
 4302            } => {
 4303                window.invalidate_character_coordinates();
 4304
 4305                pane.update(cx, |pane, _| {
 4306                    pane.track_alternate_file_items();
 4307                });
 4308                if *local {
 4309                    self.unfollow_in_pane(pane, window, cx);
 4310                }
 4311                serialize_workspace = *focus_changed || pane != self.active_pane();
 4312                if pane == self.active_pane() {
 4313                    self.active_item_path_changed(*focus_changed, window, cx);
 4314                    self.update_active_view_for_followers(window, cx);
 4315                } else if *local {
 4316                    self.set_active_pane(pane, window, cx);
 4317                }
 4318            }
 4319            pane::Event::UserSavedItem { item, save_intent } => {
 4320                cx.emit(Event::UserSavedItem {
 4321                    pane: pane.downgrade(),
 4322                    item: item.boxed_clone(),
 4323                    save_intent: *save_intent,
 4324                });
 4325                serialize_workspace = false;
 4326            }
 4327            pane::Event::ChangeItemTitle => {
 4328                if *pane == self.active_pane {
 4329                    self.active_item_path_changed(false, window, cx);
 4330                }
 4331                serialize_workspace = false;
 4332            }
 4333            pane::Event::RemovedItem { item } => {
 4334                cx.emit(Event::ActiveItemChanged);
 4335                self.update_window_edited(window, cx);
 4336                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4337                    && entry.get().entity_id() == pane.entity_id()
 4338                {
 4339                    entry.remove();
 4340                }
 4341                cx.emit(Event::ItemRemoved {
 4342                    item_id: item.item_id(),
 4343                });
 4344            }
 4345            pane::Event::Focus => {
 4346                window.invalidate_character_coordinates();
 4347                self.handle_pane_focused(pane.clone(), window, cx);
 4348            }
 4349            pane::Event::ZoomIn => {
 4350                if *pane == self.active_pane {
 4351                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4352                    if pane.read(cx).has_focus(window, cx) {
 4353                        self.zoomed = Some(pane.downgrade().into());
 4354                        self.zoomed_position = None;
 4355                        cx.emit(Event::ZoomChanged);
 4356                    }
 4357                    cx.notify();
 4358                }
 4359            }
 4360            pane::Event::ZoomOut => {
 4361                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4362                if self.zoomed_position.is_none() {
 4363                    self.zoomed = None;
 4364                    cx.emit(Event::ZoomChanged);
 4365                }
 4366                cx.notify();
 4367            }
 4368            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4369        }
 4370
 4371        if serialize_workspace {
 4372            self.serialize_workspace(window, cx);
 4373        }
 4374    }
 4375
 4376    pub fn unfollow_in_pane(
 4377        &mut self,
 4378        pane: &Entity<Pane>,
 4379        window: &mut Window,
 4380        cx: &mut Context<Workspace>,
 4381    ) -> Option<CollaboratorId> {
 4382        let leader_id = self.leader_for_pane(pane)?;
 4383        self.unfollow(leader_id, window, cx);
 4384        Some(leader_id)
 4385    }
 4386
 4387    pub fn split_pane(
 4388        &mut self,
 4389        pane_to_split: Entity<Pane>,
 4390        split_direction: SplitDirection,
 4391        window: &mut Window,
 4392        cx: &mut Context<Self>,
 4393    ) -> Entity<Pane> {
 4394        let new_pane = self.add_pane(window, cx);
 4395        self.center
 4396            .split(&pane_to_split, &new_pane, split_direction, cx)
 4397            .unwrap();
 4398        cx.notify();
 4399        new_pane
 4400    }
 4401
 4402    pub fn split_and_move(
 4403        &mut self,
 4404        pane: Entity<Pane>,
 4405        direction: SplitDirection,
 4406        window: &mut Window,
 4407        cx: &mut Context<Self>,
 4408    ) {
 4409        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4410            return;
 4411        };
 4412        let new_pane = self.add_pane(window, cx);
 4413        new_pane.update(cx, |pane, cx| {
 4414            pane.add_item(item, true, true, None, window, cx)
 4415        });
 4416        self.center.split(&pane, &new_pane, direction, cx).unwrap();
 4417        cx.notify();
 4418    }
 4419
 4420    pub fn split_and_clone(
 4421        &mut self,
 4422        pane: Entity<Pane>,
 4423        direction: SplitDirection,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) -> Task<Option<Entity<Pane>>> {
 4427        let Some(item) = pane.read(cx).active_item() else {
 4428            return Task::ready(None);
 4429        };
 4430        if !item.can_split(cx) {
 4431            return Task::ready(None);
 4432        }
 4433        let task = item.clone_on_split(self.database_id(), window, cx);
 4434        cx.spawn_in(window, async move |this, cx| {
 4435            if let Some(clone) = task.await {
 4436                this.update_in(cx, |this, window, cx| {
 4437                    let new_pane = this.add_pane(window, cx);
 4438                    new_pane.update(cx, |pane, cx| {
 4439                        pane.add_item(clone, true, true, None, window, cx)
 4440                    });
 4441                    this.center.split(&pane, &new_pane, direction, cx).unwrap();
 4442                    cx.notify();
 4443                    new_pane
 4444                })
 4445                .ok()
 4446            } else {
 4447                None
 4448            }
 4449        })
 4450    }
 4451
 4452    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4453        let active_item = self.active_pane.read(cx).active_item();
 4454        for pane in &self.panes {
 4455            join_pane_into_active(&self.active_pane, pane, window, cx);
 4456        }
 4457        if let Some(active_item) = active_item {
 4458            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4459        }
 4460        cx.notify();
 4461    }
 4462
 4463    pub fn join_pane_into_next(
 4464        &mut self,
 4465        pane: Entity<Pane>,
 4466        window: &mut Window,
 4467        cx: &mut Context<Self>,
 4468    ) {
 4469        let next_pane = self
 4470            .find_pane_in_direction(SplitDirection::Right, cx)
 4471            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4472            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4473            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4474        let Some(next_pane) = next_pane else {
 4475            return;
 4476        };
 4477        move_all_items(&pane, &next_pane, window, cx);
 4478        cx.notify();
 4479    }
 4480
 4481    fn remove_pane(
 4482        &mut self,
 4483        pane: Entity<Pane>,
 4484        focus_on: Option<Entity<Pane>>,
 4485        window: &mut Window,
 4486        cx: &mut Context<Self>,
 4487    ) {
 4488        if self.center.remove(&pane, cx).unwrap() {
 4489            self.force_remove_pane(&pane, &focus_on, window, cx);
 4490            self.unfollow_in_pane(&pane, window, cx);
 4491            self.last_leaders_by_pane.remove(&pane.downgrade());
 4492            for removed_item in pane.read(cx).items() {
 4493                self.panes_by_item.remove(&removed_item.item_id());
 4494            }
 4495
 4496            cx.notify();
 4497        } else {
 4498            self.active_item_path_changed(true, window, cx);
 4499        }
 4500        cx.emit(Event::PaneRemoved);
 4501    }
 4502
 4503    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4504        &mut self.panes
 4505    }
 4506
 4507    pub fn panes(&self) -> &[Entity<Pane>] {
 4508        &self.panes
 4509    }
 4510
 4511    pub fn active_pane(&self) -> &Entity<Pane> {
 4512        &self.active_pane
 4513    }
 4514
 4515    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4516        for dock in self.all_docks() {
 4517            if dock.focus_handle(cx).contains_focused(window, cx)
 4518                && let Some(pane) = dock
 4519                    .read(cx)
 4520                    .active_panel()
 4521                    .and_then(|panel| panel.pane(cx))
 4522            {
 4523                return pane;
 4524            }
 4525        }
 4526        self.active_pane().clone()
 4527    }
 4528
 4529    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4530        self.find_pane_in_direction(SplitDirection::Right, cx)
 4531            .unwrap_or_else(|| {
 4532                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4533            })
 4534    }
 4535
 4536    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4537        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4538        weak_pane.upgrade()
 4539    }
 4540
 4541    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4542        self.follower_states.retain(|leader_id, state| {
 4543            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4544                for item in state.items_by_leader_view_id.values() {
 4545                    item.view.set_leader_id(None, window, cx);
 4546                }
 4547                false
 4548            } else {
 4549                true
 4550            }
 4551        });
 4552        cx.notify();
 4553    }
 4554
 4555    pub fn start_following(
 4556        &mut self,
 4557        leader_id: impl Into<CollaboratorId>,
 4558        window: &mut Window,
 4559        cx: &mut Context<Self>,
 4560    ) -> Option<Task<Result<()>>> {
 4561        let leader_id = leader_id.into();
 4562        let pane = self.active_pane().clone();
 4563
 4564        self.last_leaders_by_pane
 4565            .insert(pane.downgrade(), leader_id);
 4566        self.unfollow(leader_id, window, cx);
 4567        self.unfollow_in_pane(&pane, window, cx);
 4568        self.follower_states.insert(
 4569            leader_id,
 4570            FollowerState {
 4571                center_pane: pane.clone(),
 4572                dock_pane: None,
 4573                active_view_id: None,
 4574                items_by_leader_view_id: Default::default(),
 4575            },
 4576        );
 4577        cx.notify();
 4578
 4579        match leader_id {
 4580            CollaboratorId::PeerId(leader_peer_id) => {
 4581                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4582                let project_id = self.project.read(cx).remote_id();
 4583                let request = self.app_state.client.request(proto::Follow {
 4584                    room_id,
 4585                    project_id,
 4586                    leader_id: Some(leader_peer_id),
 4587                });
 4588
 4589                Some(cx.spawn_in(window, async move |this, cx| {
 4590                    let response = request.await?;
 4591                    this.update(cx, |this, _| {
 4592                        let state = this
 4593                            .follower_states
 4594                            .get_mut(&leader_id)
 4595                            .context("following interrupted")?;
 4596                        state.active_view_id = response
 4597                            .active_view
 4598                            .as_ref()
 4599                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4600                        anyhow::Ok(())
 4601                    })??;
 4602                    if let Some(view) = response.active_view {
 4603                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4604                    }
 4605                    this.update_in(cx, |this, window, cx| {
 4606                        this.leader_updated(leader_id, window, cx)
 4607                    })?;
 4608                    Ok(())
 4609                }))
 4610            }
 4611            CollaboratorId::Agent => {
 4612                self.leader_updated(leader_id, window, cx)?;
 4613                Some(Task::ready(Ok(())))
 4614            }
 4615        }
 4616    }
 4617
 4618    pub fn follow_next_collaborator(
 4619        &mut self,
 4620        _: &FollowNextCollaborator,
 4621        window: &mut Window,
 4622        cx: &mut Context<Self>,
 4623    ) {
 4624        let collaborators = self.project.read(cx).collaborators();
 4625        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4626            let mut collaborators = collaborators.keys().copied();
 4627            for peer_id in collaborators.by_ref() {
 4628                if CollaboratorId::PeerId(peer_id) == leader_id {
 4629                    break;
 4630                }
 4631            }
 4632            collaborators.next().map(CollaboratorId::PeerId)
 4633        } else if let Some(last_leader_id) =
 4634            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4635        {
 4636            match last_leader_id {
 4637                CollaboratorId::PeerId(peer_id) => {
 4638                    if collaborators.contains_key(peer_id) {
 4639                        Some(*last_leader_id)
 4640                    } else {
 4641                        None
 4642                    }
 4643                }
 4644                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4645            }
 4646        } else {
 4647            None
 4648        };
 4649
 4650        let pane = self.active_pane.clone();
 4651        let Some(leader_id) = next_leader_id.or_else(|| {
 4652            Some(CollaboratorId::PeerId(
 4653                collaborators.keys().copied().next()?,
 4654            ))
 4655        }) else {
 4656            return;
 4657        };
 4658        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4659            return;
 4660        }
 4661        if let Some(task) = self.start_following(leader_id, window, cx) {
 4662            task.detach_and_log_err(cx)
 4663        }
 4664    }
 4665
 4666    pub fn follow(
 4667        &mut self,
 4668        leader_id: impl Into<CollaboratorId>,
 4669        window: &mut Window,
 4670        cx: &mut Context<Self>,
 4671    ) {
 4672        let leader_id = leader_id.into();
 4673
 4674        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4675            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4676                return;
 4677            };
 4678            let room = room.read(cx);
 4679            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4680                return;
 4681            };
 4682
 4683            let project = self.project.read(cx);
 4684
 4685            let other_project_id = match remote_participant.location {
 4686                call::ParticipantLocation::External => None,
 4687                call::ParticipantLocation::UnsharedProject => None,
 4688                call::ParticipantLocation::SharedProject { project_id } => {
 4689                    if Some(project_id) == project.remote_id() {
 4690                        None
 4691                    } else {
 4692                        Some(project_id)
 4693                    }
 4694                }
 4695            };
 4696
 4697            // if they are active in another project, follow there.
 4698            if let Some(project_id) = other_project_id {
 4699                let app_state = self.app_state.clone();
 4700                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4701                    .detach_and_log_err(cx);
 4702            }
 4703        }
 4704
 4705        // if you're already following, find the right pane and focus it.
 4706        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4707            window.focus(&follower_state.pane().focus_handle(cx), cx);
 4708
 4709            return;
 4710        }
 4711
 4712        // Otherwise, follow.
 4713        if let Some(task) = self.start_following(leader_id, window, cx) {
 4714            task.detach_and_log_err(cx)
 4715        }
 4716    }
 4717
 4718    pub fn unfollow(
 4719        &mut self,
 4720        leader_id: impl Into<CollaboratorId>,
 4721        window: &mut Window,
 4722        cx: &mut Context<Self>,
 4723    ) -> Option<()> {
 4724        cx.notify();
 4725
 4726        let leader_id = leader_id.into();
 4727        let state = self.follower_states.remove(&leader_id)?;
 4728        for (_, item) in state.items_by_leader_view_id {
 4729            item.view.set_leader_id(None, window, cx);
 4730        }
 4731
 4732        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4733            let project_id = self.project.read(cx).remote_id();
 4734            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4735            self.app_state
 4736                .client
 4737                .send(proto::Unfollow {
 4738                    room_id,
 4739                    project_id,
 4740                    leader_id: Some(leader_peer_id),
 4741                })
 4742                .log_err();
 4743        }
 4744
 4745        Some(())
 4746    }
 4747
 4748    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4749        self.follower_states.contains_key(&id.into())
 4750    }
 4751
 4752    fn active_item_path_changed(
 4753        &mut self,
 4754        focus_changed: bool,
 4755        window: &mut Window,
 4756        cx: &mut Context<Self>,
 4757    ) {
 4758        cx.emit(Event::ActiveItemChanged);
 4759        let active_entry = self.active_project_path(cx);
 4760        self.project.update(cx, |project, cx| {
 4761            project.set_active_path(active_entry.clone(), cx)
 4762        });
 4763
 4764        if focus_changed && let Some(project_path) = &active_entry {
 4765            let git_store_entity = self.project.read(cx).git_store().clone();
 4766            git_store_entity.update(cx, |git_store, cx| {
 4767                git_store.set_active_repo_for_path(project_path, cx);
 4768            });
 4769        }
 4770
 4771        self.update_window_title(window, cx);
 4772    }
 4773
 4774    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4775        let project = self.project().read(cx);
 4776        let mut title = String::new();
 4777
 4778        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 4779            let name = {
 4780                let settings_location = SettingsLocation {
 4781                    worktree_id: worktree.read(cx).id(),
 4782                    path: RelPath::empty(),
 4783                };
 4784
 4785                let settings = WorktreeSettings::get(Some(settings_location), cx);
 4786                match &settings.project_name {
 4787                    Some(name) => name.as_str(),
 4788                    None => worktree.read(cx).root_name_str(),
 4789                }
 4790            };
 4791            if i > 0 {
 4792                title.push_str(", ");
 4793            }
 4794            title.push_str(name);
 4795        }
 4796
 4797        if title.is_empty() {
 4798            title = "empty project".to_string();
 4799        }
 4800
 4801        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4802            let filename = path.path.file_name().or_else(|| {
 4803                Some(
 4804                    project
 4805                        .worktree_for_id(path.worktree_id, cx)?
 4806                        .read(cx)
 4807                        .root_name_str(),
 4808                )
 4809            });
 4810
 4811            if let Some(filename) = filename {
 4812                title.push_str("");
 4813                title.push_str(filename.as_ref());
 4814            }
 4815        }
 4816
 4817        if project.is_via_collab() {
 4818            title.push_str("");
 4819        } else if project.is_shared() {
 4820            title.push_str("");
 4821        }
 4822
 4823        if let Some(last_title) = self.last_window_title.as_ref()
 4824            && &title == last_title
 4825        {
 4826            return;
 4827        }
 4828        window.set_window_title(&title);
 4829        SystemWindowTabController::update_tab_title(
 4830            cx,
 4831            window.window_handle().window_id(),
 4832            SharedString::from(&title),
 4833        );
 4834        self.last_window_title = Some(title);
 4835    }
 4836
 4837    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4838        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4839        if is_edited != self.window_edited {
 4840            self.window_edited = is_edited;
 4841            window.set_window_edited(self.window_edited)
 4842        }
 4843    }
 4844
 4845    fn update_item_dirty_state(
 4846        &mut self,
 4847        item: &dyn ItemHandle,
 4848        window: &mut Window,
 4849        cx: &mut App,
 4850    ) {
 4851        let is_dirty = item.is_dirty(cx);
 4852        let item_id = item.item_id();
 4853        let was_dirty = self.dirty_items.contains_key(&item_id);
 4854        if is_dirty == was_dirty {
 4855            return;
 4856        }
 4857        if was_dirty {
 4858            self.dirty_items.remove(&item_id);
 4859            self.update_window_edited(window, cx);
 4860            return;
 4861        }
 4862        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4863            let s = item.on_release(
 4864                cx,
 4865                Box::new(move |cx| {
 4866                    window_handle
 4867                        .update(cx, |this, window, cx| {
 4868                            this.dirty_items.remove(&item_id);
 4869                            this.update_window_edited(window, cx)
 4870                        })
 4871                        .ok();
 4872                }),
 4873            );
 4874            self.dirty_items.insert(item_id, s);
 4875            self.update_window_edited(window, cx);
 4876        }
 4877    }
 4878
 4879    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4880        if self.notifications.is_empty() {
 4881            None
 4882        } else {
 4883            Some(
 4884                div()
 4885                    .absolute()
 4886                    .right_3()
 4887                    .bottom_3()
 4888                    .w_112()
 4889                    .h_full()
 4890                    .flex()
 4891                    .flex_col()
 4892                    .justify_end()
 4893                    .gap_2()
 4894                    .children(
 4895                        self.notifications
 4896                            .iter()
 4897                            .map(|(_, notification)| notification.clone().into_any()),
 4898                    ),
 4899            )
 4900        }
 4901    }
 4902
 4903    // RPC handlers
 4904
 4905    fn active_view_for_follower(
 4906        &self,
 4907        follower_project_id: Option<u64>,
 4908        window: &mut Window,
 4909        cx: &mut Context<Self>,
 4910    ) -> Option<proto::View> {
 4911        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4912        let item = item?;
 4913        let leader_id = self
 4914            .pane_for(&*item)
 4915            .and_then(|pane| self.leader_for_pane(&pane));
 4916        let leader_peer_id = match leader_id {
 4917            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4918            Some(CollaboratorId::Agent) | None => None,
 4919        };
 4920
 4921        let item_handle = item.to_followable_item_handle(cx)?;
 4922        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4923        let variant = item_handle.to_state_proto(window, cx)?;
 4924
 4925        if item_handle.is_project_item(window, cx)
 4926            && (follower_project_id.is_none()
 4927                || follower_project_id != self.project.read(cx).remote_id())
 4928        {
 4929            return None;
 4930        }
 4931
 4932        Some(proto::View {
 4933            id: id.to_proto(),
 4934            leader_id: leader_peer_id,
 4935            variant: Some(variant),
 4936            panel_id: panel_id.map(|id| id as i32),
 4937        })
 4938    }
 4939
 4940    fn handle_follow(
 4941        &mut self,
 4942        follower_project_id: Option<u64>,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) -> proto::FollowResponse {
 4946        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4947
 4948        cx.notify();
 4949        proto::FollowResponse {
 4950            // TODO: Remove after version 0.145.x stabilizes.
 4951            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4952            views: active_view.iter().cloned().collect(),
 4953            active_view,
 4954        }
 4955    }
 4956
 4957    fn handle_update_followers(
 4958        &mut self,
 4959        leader_id: PeerId,
 4960        message: proto::UpdateFollowers,
 4961        _window: &mut Window,
 4962        _cx: &mut Context<Self>,
 4963    ) {
 4964        self.leader_updates_tx
 4965            .unbounded_send((leader_id, message))
 4966            .ok();
 4967    }
 4968
 4969    async fn process_leader_update(
 4970        this: &WeakEntity<Self>,
 4971        leader_id: PeerId,
 4972        update: proto::UpdateFollowers,
 4973        cx: &mut AsyncWindowContext,
 4974    ) -> Result<()> {
 4975        match update.variant.context("invalid update")? {
 4976            proto::update_followers::Variant::CreateView(view) => {
 4977                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4978                let should_add_view = this.update(cx, |this, _| {
 4979                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4980                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4981                    } else {
 4982                        anyhow::Ok(false)
 4983                    }
 4984                })??;
 4985
 4986                if should_add_view {
 4987                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4988                }
 4989            }
 4990            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4991                let should_add_view = this.update(cx, |this, _| {
 4992                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4993                        state.active_view_id = update_active_view
 4994                            .view
 4995                            .as_ref()
 4996                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4997
 4998                        if state.active_view_id.is_some_and(|view_id| {
 4999                            !state.items_by_leader_view_id.contains_key(&view_id)
 5000                        }) {
 5001                            anyhow::Ok(true)
 5002                        } else {
 5003                            anyhow::Ok(false)
 5004                        }
 5005                    } else {
 5006                        anyhow::Ok(false)
 5007                    }
 5008                })??;
 5009
 5010                if should_add_view && let Some(view) = update_active_view.view {
 5011                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5012                }
 5013            }
 5014            proto::update_followers::Variant::UpdateView(update_view) => {
 5015                let variant = update_view.variant.context("missing update view variant")?;
 5016                let id = update_view.id.context("missing update view id")?;
 5017                let mut tasks = Vec::new();
 5018                this.update_in(cx, |this, window, cx| {
 5019                    let project = this.project.clone();
 5020                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5021                        let view_id = ViewId::from_proto(id.clone())?;
 5022                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5023                            tasks.push(item.view.apply_update_proto(
 5024                                &project,
 5025                                variant.clone(),
 5026                                window,
 5027                                cx,
 5028                            ));
 5029                        }
 5030                    }
 5031                    anyhow::Ok(())
 5032                })??;
 5033                try_join_all(tasks).await.log_err();
 5034            }
 5035        }
 5036        this.update_in(cx, |this, window, cx| {
 5037            this.leader_updated(leader_id, window, cx)
 5038        })?;
 5039        Ok(())
 5040    }
 5041
 5042    async fn add_view_from_leader(
 5043        this: WeakEntity<Self>,
 5044        leader_id: PeerId,
 5045        view: &proto::View,
 5046        cx: &mut AsyncWindowContext,
 5047    ) -> Result<()> {
 5048        let this = this.upgrade().context("workspace dropped")?;
 5049
 5050        let Some(id) = view.id.clone() else {
 5051            anyhow::bail!("no id for view");
 5052        };
 5053        let id = ViewId::from_proto(id)?;
 5054        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5055
 5056        let pane = this.update(cx, |this, _cx| {
 5057            let state = this
 5058                .follower_states
 5059                .get(&leader_id.into())
 5060                .context("stopped following")?;
 5061            anyhow::Ok(state.pane().clone())
 5062        })??;
 5063        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5064            let client = this.read(cx).client().clone();
 5065            pane.items().find_map(|item| {
 5066                let item = item.to_followable_item_handle(cx)?;
 5067                if item.remote_id(&client, window, cx) == Some(id) {
 5068                    Some(item)
 5069                } else {
 5070                    None
 5071                }
 5072            })
 5073        })?;
 5074        let item = if let Some(existing_item) = existing_item {
 5075            existing_item
 5076        } else {
 5077            let variant = view.variant.clone();
 5078            anyhow::ensure!(variant.is_some(), "missing view variant");
 5079
 5080            let task = cx.update(|window, cx| {
 5081                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5082            })?;
 5083
 5084            let Some(task) = task else {
 5085                anyhow::bail!(
 5086                    "failed to construct view from leader (maybe from a different version of zed?)"
 5087                );
 5088            };
 5089
 5090            let mut new_item = task.await?;
 5091            pane.update_in(cx, |pane, window, cx| {
 5092                let mut item_to_remove = None;
 5093                for (ix, item) in pane.items().enumerate() {
 5094                    if let Some(item) = item.to_followable_item_handle(cx) {
 5095                        match new_item.dedup(item.as_ref(), window, cx) {
 5096                            Some(item::Dedup::KeepExisting) => {
 5097                                new_item =
 5098                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5099                                break;
 5100                            }
 5101                            Some(item::Dedup::ReplaceExisting) => {
 5102                                item_to_remove = Some((ix, item.item_id()));
 5103                                break;
 5104                            }
 5105                            None => {}
 5106                        }
 5107                    }
 5108                }
 5109
 5110                if let Some((ix, id)) = item_to_remove {
 5111                    pane.remove_item(id, false, false, window, cx);
 5112                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5113                }
 5114            })?;
 5115
 5116            new_item
 5117        };
 5118
 5119        this.update_in(cx, |this, window, cx| {
 5120            let state = this.follower_states.get_mut(&leader_id.into())?;
 5121            item.set_leader_id(Some(leader_id.into()), window, cx);
 5122            state.items_by_leader_view_id.insert(
 5123                id,
 5124                FollowerView {
 5125                    view: item,
 5126                    location: panel_id,
 5127                },
 5128            );
 5129
 5130            Some(())
 5131        })?;
 5132
 5133        Ok(())
 5134    }
 5135
 5136    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5137        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5138            return;
 5139        };
 5140
 5141        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5142            let buffer_entity_id = agent_location.buffer.entity_id();
 5143            let view_id = ViewId {
 5144                creator: CollaboratorId::Agent,
 5145                id: buffer_entity_id.as_u64(),
 5146            };
 5147            follower_state.active_view_id = Some(view_id);
 5148
 5149            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5150                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5151                hash_map::Entry::Vacant(entry) => {
 5152                    let existing_view =
 5153                        follower_state
 5154                            .center_pane
 5155                            .read(cx)
 5156                            .items()
 5157                            .find_map(|item| {
 5158                                let item = item.to_followable_item_handle(cx)?;
 5159                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5160                                    && item.project_item_model_ids(cx).as_slice()
 5161                                        == [buffer_entity_id]
 5162                                {
 5163                                    Some(item)
 5164                                } else {
 5165                                    None
 5166                                }
 5167                            });
 5168                    let view = existing_view.or_else(|| {
 5169                        agent_location.buffer.upgrade().and_then(|buffer| {
 5170                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5171                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5172                            })?
 5173                            .to_followable_item_handle(cx)
 5174                        })
 5175                    });
 5176
 5177                    view.map(|view| {
 5178                        entry.insert(FollowerView {
 5179                            view,
 5180                            location: None,
 5181                        })
 5182                    })
 5183                }
 5184            };
 5185
 5186            if let Some(item) = item {
 5187                item.view
 5188                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5189                item.view
 5190                    .update_agent_location(agent_location.position, window, cx);
 5191            }
 5192        } else {
 5193            follower_state.active_view_id = None;
 5194        }
 5195
 5196        self.leader_updated(CollaboratorId::Agent, window, cx);
 5197    }
 5198
 5199    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5200        let mut is_project_item = true;
 5201        let mut update = proto::UpdateActiveView::default();
 5202        if window.is_window_active() {
 5203            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5204
 5205            if let Some(item) = active_item
 5206                && item.item_focus_handle(cx).contains_focused(window, cx)
 5207            {
 5208                let leader_id = self
 5209                    .pane_for(&*item)
 5210                    .and_then(|pane| self.leader_for_pane(&pane));
 5211                let leader_peer_id = match leader_id {
 5212                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5213                    Some(CollaboratorId::Agent) | None => None,
 5214                };
 5215
 5216                if let Some(item) = item.to_followable_item_handle(cx) {
 5217                    let id = item
 5218                        .remote_id(&self.app_state.client, window, cx)
 5219                        .map(|id| id.to_proto());
 5220
 5221                    if let Some(id) = id
 5222                        && let Some(variant) = item.to_state_proto(window, cx)
 5223                    {
 5224                        let view = Some(proto::View {
 5225                            id: id.clone(),
 5226                            leader_id: leader_peer_id,
 5227                            variant: Some(variant),
 5228                            panel_id: panel_id.map(|id| id as i32),
 5229                        });
 5230
 5231                        is_project_item = item.is_project_item(window, cx);
 5232                        update = proto::UpdateActiveView {
 5233                            view,
 5234                            // TODO: Remove after version 0.145.x stabilizes.
 5235                            id,
 5236                            leader_id: leader_peer_id,
 5237                        };
 5238                    };
 5239                }
 5240            }
 5241        }
 5242
 5243        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5244        if active_view_id != self.last_active_view_id.as_ref() {
 5245            self.last_active_view_id = active_view_id.cloned();
 5246            self.update_followers(
 5247                is_project_item,
 5248                proto::update_followers::Variant::UpdateActiveView(update),
 5249                window,
 5250                cx,
 5251            );
 5252        }
 5253    }
 5254
 5255    fn active_item_for_followers(
 5256        &self,
 5257        window: &mut Window,
 5258        cx: &mut App,
 5259    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5260        let mut active_item = None;
 5261        let mut panel_id = None;
 5262        for dock in self.all_docks() {
 5263            if dock.focus_handle(cx).contains_focused(window, cx)
 5264                && let Some(panel) = dock.read(cx).active_panel()
 5265                && let Some(pane) = panel.pane(cx)
 5266                && let Some(item) = pane.read(cx).active_item()
 5267            {
 5268                active_item = Some(item);
 5269                panel_id = panel.remote_id();
 5270                break;
 5271            }
 5272        }
 5273
 5274        if active_item.is_none() {
 5275            active_item = self.active_pane().read(cx).active_item();
 5276        }
 5277        (active_item, panel_id)
 5278    }
 5279
 5280    fn update_followers(
 5281        &self,
 5282        project_only: bool,
 5283        update: proto::update_followers::Variant,
 5284        _: &mut Window,
 5285        cx: &mut App,
 5286    ) -> Option<()> {
 5287        // If this update only applies to for followers in the current project,
 5288        // then skip it unless this project is shared. If it applies to all
 5289        // followers, regardless of project, then set `project_id` to none,
 5290        // indicating that it goes to all followers.
 5291        let project_id = if project_only {
 5292            Some(self.project.read(cx).remote_id()?)
 5293        } else {
 5294            None
 5295        };
 5296        self.app_state().workspace_store.update(cx, |store, cx| {
 5297            store.update_followers(project_id, update, cx)
 5298        })
 5299    }
 5300
 5301    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5302        self.follower_states.iter().find_map(|(leader_id, state)| {
 5303            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5304                Some(*leader_id)
 5305            } else {
 5306                None
 5307            }
 5308        })
 5309    }
 5310
 5311    fn leader_updated(
 5312        &mut self,
 5313        leader_id: impl Into<CollaboratorId>,
 5314        window: &mut Window,
 5315        cx: &mut Context<Self>,
 5316    ) -> Option<Box<dyn ItemHandle>> {
 5317        cx.notify();
 5318
 5319        let leader_id = leader_id.into();
 5320        let (panel_id, item) = match leader_id {
 5321            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5322            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5323        };
 5324
 5325        let state = self.follower_states.get(&leader_id)?;
 5326        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5327        let pane;
 5328        if let Some(panel_id) = panel_id {
 5329            pane = self
 5330                .activate_panel_for_proto_id(panel_id, window, cx)?
 5331                .pane(cx)?;
 5332            let state = self.follower_states.get_mut(&leader_id)?;
 5333            state.dock_pane = Some(pane.clone());
 5334        } else {
 5335            pane = state.center_pane.clone();
 5336            let state = self.follower_states.get_mut(&leader_id)?;
 5337            if let Some(dock_pane) = state.dock_pane.take() {
 5338                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5339            }
 5340        }
 5341
 5342        pane.update(cx, |pane, cx| {
 5343            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5344            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5345                pane.activate_item(index, false, false, window, cx);
 5346            } else {
 5347                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5348            }
 5349
 5350            if focus_active_item {
 5351                pane.focus_active_item(window, cx)
 5352            }
 5353        });
 5354
 5355        Some(item)
 5356    }
 5357
 5358    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5359        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5360        let active_view_id = state.active_view_id?;
 5361        Some(
 5362            state
 5363                .items_by_leader_view_id
 5364                .get(&active_view_id)?
 5365                .view
 5366                .boxed_clone(),
 5367        )
 5368    }
 5369
 5370    fn active_item_for_peer(
 5371        &self,
 5372        peer_id: PeerId,
 5373        window: &mut Window,
 5374        cx: &mut Context<Self>,
 5375    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5376        let call = self.active_call()?;
 5377        let room = call.read(cx).room()?.read(cx);
 5378        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5379        let leader_in_this_app;
 5380        let leader_in_this_project;
 5381        match participant.location {
 5382            call::ParticipantLocation::SharedProject { project_id } => {
 5383                leader_in_this_app = true;
 5384                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5385            }
 5386            call::ParticipantLocation::UnsharedProject => {
 5387                leader_in_this_app = true;
 5388                leader_in_this_project = false;
 5389            }
 5390            call::ParticipantLocation::External => {
 5391                leader_in_this_app = false;
 5392                leader_in_this_project = false;
 5393            }
 5394        };
 5395        let state = self.follower_states.get(&peer_id.into())?;
 5396        let mut item_to_activate = None;
 5397        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5398            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5399                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5400            {
 5401                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5402            }
 5403        } else if let Some(shared_screen) =
 5404            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5405        {
 5406            item_to_activate = Some((None, Box::new(shared_screen)));
 5407        }
 5408        item_to_activate
 5409    }
 5410
 5411    fn shared_screen_for_peer(
 5412        &self,
 5413        peer_id: PeerId,
 5414        pane: &Entity<Pane>,
 5415        window: &mut Window,
 5416        cx: &mut App,
 5417    ) -> Option<Entity<SharedScreen>> {
 5418        let call = self.active_call()?;
 5419        let room = call.read(cx).room()?.clone();
 5420        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5421        let track = participant.video_tracks.values().next()?.clone();
 5422        let user = participant.user.clone();
 5423
 5424        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5425            if item.read(cx).peer_id == peer_id {
 5426                return Some(item);
 5427            }
 5428        }
 5429
 5430        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5431    }
 5432
 5433    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5434        if window.is_window_active() {
 5435            self.update_active_view_for_followers(window, cx);
 5436
 5437            if let Some(database_id) = self.database_id {
 5438                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5439                    .detach();
 5440            }
 5441        } else {
 5442            for pane in &self.panes {
 5443                pane.update(cx, |pane, cx| {
 5444                    if let Some(item) = pane.active_item() {
 5445                        item.workspace_deactivated(window, cx);
 5446                    }
 5447                    for item in pane.items() {
 5448                        if matches!(
 5449                            item.workspace_settings(cx).autosave,
 5450                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5451                        ) {
 5452                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5453                                .detach_and_log_err(cx);
 5454                        }
 5455                    }
 5456                });
 5457            }
 5458        }
 5459    }
 5460
 5461    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5462        self.active_call.as_ref().map(|(call, _)| call)
 5463    }
 5464
 5465    fn on_active_call_event(
 5466        &mut self,
 5467        _: &Entity<ActiveCall>,
 5468        event: &call::room::Event,
 5469        window: &mut Window,
 5470        cx: &mut Context<Self>,
 5471    ) {
 5472        match event {
 5473            call::room::Event::ParticipantLocationChanged { participant_id }
 5474            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5475                self.leader_updated(participant_id, window, cx);
 5476            }
 5477            _ => {}
 5478        }
 5479    }
 5480
 5481    pub fn database_id(&self) -> Option<WorkspaceId> {
 5482        self.database_id
 5483    }
 5484
 5485    pub fn session_id(&self) -> Option<String> {
 5486        self.session_id.clone()
 5487    }
 5488
 5489    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5490        let project = self.project().read(cx);
 5491        project
 5492            .visible_worktrees(cx)
 5493            .map(|worktree| worktree.read(cx).abs_path())
 5494            .collect::<Vec<_>>()
 5495    }
 5496
 5497    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5498        match member {
 5499            Member::Axis(PaneAxis { members, .. }) => {
 5500                for child in members.iter() {
 5501                    self.remove_panes(child.clone(), window, cx)
 5502                }
 5503            }
 5504            Member::Pane(pane) => {
 5505                self.force_remove_pane(&pane, &None, window, cx);
 5506            }
 5507        }
 5508    }
 5509
 5510    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5511        self.session_id.take();
 5512        self.serialize_workspace_internal(window, cx)
 5513    }
 5514
 5515    fn force_remove_pane(
 5516        &mut self,
 5517        pane: &Entity<Pane>,
 5518        focus_on: &Option<Entity<Pane>>,
 5519        window: &mut Window,
 5520        cx: &mut Context<Workspace>,
 5521    ) {
 5522        self.panes.retain(|p| p != pane);
 5523        if let Some(focus_on) = focus_on {
 5524            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5525        } else if self.active_pane() == pane {
 5526            self.panes
 5527                .last()
 5528                .unwrap()
 5529                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5530        }
 5531        if self.last_active_center_pane == Some(pane.downgrade()) {
 5532            self.last_active_center_pane = None;
 5533        }
 5534        cx.notify();
 5535    }
 5536
 5537    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5538        if self._schedule_serialize_workspace.is_none() {
 5539            self._schedule_serialize_workspace =
 5540                Some(cx.spawn_in(window, async move |this, cx| {
 5541                    cx.background_executor()
 5542                        .timer(SERIALIZATION_THROTTLE_TIME)
 5543                        .await;
 5544                    this.update_in(cx, |this, window, cx| {
 5545                        this.serialize_workspace_internal(window, cx).detach();
 5546                        this._schedule_serialize_workspace.take();
 5547                    })
 5548                    .log_err();
 5549                }));
 5550        }
 5551    }
 5552
 5553    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5554        let Some(database_id) = self.database_id() else {
 5555            return Task::ready(());
 5556        };
 5557
 5558        fn serialize_pane_handle(
 5559            pane_handle: &Entity<Pane>,
 5560            window: &mut Window,
 5561            cx: &mut App,
 5562        ) -> SerializedPane {
 5563            let (items, active, pinned_count) = {
 5564                let pane = pane_handle.read(cx);
 5565                let active_item_id = pane.active_item().map(|item| item.item_id());
 5566                (
 5567                    pane.items()
 5568                        .filter_map(|handle| {
 5569                            let handle = handle.to_serializable_item_handle(cx)?;
 5570
 5571                            Some(SerializedItem {
 5572                                kind: Arc::from(handle.serialized_item_kind()),
 5573                                item_id: handle.item_id().as_u64(),
 5574                                active: Some(handle.item_id()) == active_item_id,
 5575                                preview: pane.is_active_preview_item(handle.item_id()),
 5576                            })
 5577                        })
 5578                        .collect::<Vec<_>>(),
 5579                    pane.has_focus(window, cx),
 5580                    pane.pinned_count(),
 5581                )
 5582            };
 5583
 5584            SerializedPane::new(items, active, pinned_count)
 5585        }
 5586
 5587        fn build_serialized_pane_group(
 5588            pane_group: &Member,
 5589            window: &mut Window,
 5590            cx: &mut App,
 5591        ) -> SerializedPaneGroup {
 5592            match pane_group {
 5593                Member::Axis(PaneAxis {
 5594                    axis,
 5595                    members,
 5596                    flexes,
 5597                    bounding_boxes: _,
 5598                }) => SerializedPaneGroup::Group {
 5599                    axis: SerializedAxis(*axis),
 5600                    children: members
 5601                        .iter()
 5602                        .map(|member| build_serialized_pane_group(member, window, cx))
 5603                        .collect::<Vec<_>>(),
 5604                    flexes: Some(flexes.lock().clone()),
 5605                },
 5606                Member::Pane(pane_handle) => {
 5607                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5608                }
 5609            }
 5610        }
 5611
 5612        fn build_serialized_docks(
 5613            this: &Workspace,
 5614            window: &mut Window,
 5615            cx: &mut App,
 5616        ) -> DockStructure {
 5617            let left_dock = this.left_dock.read(cx);
 5618            let left_visible = left_dock.is_open();
 5619            let left_active_panel = left_dock
 5620                .active_panel()
 5621                .map(|panel| panel.persistent_name().to_string());
 5622            let left_dock_zoom = left_dock
 5623                .active_panel()
 5624                .map(|panel| panel.is_zoomed(window, cx))
 5625                .unwrap_or(false);
 5626
 5627            let right_dock = this.right_dock.read(cx);
 5628            let right_visible = right_dock.is_open();
 5629            let right_active_panel = right_dock
 5630                .active_panel()
 5631                .map(|panel| panel.persistent_name().to_string());
 5632            let right_dock_zoom = right_dock
 5633                .active_panel()
 5634                .map(|panel| panel.is_zoomed(window, cx))
 5635                .unwrap_or(false);
 5636
 5637            let bottom_dock = this.bottom_dock.read(cx);
 5638            let bottom_visible = bottom_dock.is_open();
 5639            let bottom_active_panel = bottom_dock
 5640                .active_panel()
 5641                .map(|panel| panel.persistent_name().to_string());
 5642            let bottom_dock_zoom = bottom_dock
 5643                .active_panel()
 5644                .map(|panel| panel.is_zoomed(window, cx))
 5645                .unwrap_or(false);
 5646
 5647            DockStructure {
 5648                left: DockData {
 5649                    visible: left_visible,
 5650                    active_panel: left_active_panel,
 5651                    zoom: left_dock_zoom,
 5652                },
 5653                right: DockData {
 5654                    visible: right_visible,
 5655                    active_panel: right_active_panel,
 5656                    zoom: right_dock_zoom,
 5657                },
 5658                bottom: DockData {
 5659                    visible: bottom_visible,
 5660                    active_panel: bottom_active_panel,
 5661                    zoom: bottom_dock_zoom,
 5662                },
 5663            }
 5664        }
 5665
 5666        match self.serialize_workspace_location(cx) {
 5667            WorkspaceLocation::Location(location, paths) => {
 5668                let breakpoints = self.project.update(cx, |project, cx| {
 5669                    project
 5670                        .breakpoint_store()
 5671                        .read(cx)
 5672                        .all_source_breakpoints(cx)
 5673                });
 5674                let user_toolchains = self
 5675                    .project
 5676                    .read(cx)
 5677                    .user_toolchains(cx)
 5678                    .unwrap_or_default();
 5679
 5680                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5681                let docks = build_serialized_docks(self, window, cx);
 5682                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5683
 5684                let serialized_workspace = SerializedWorkspace {
 5685                    id: database_id,
 5686                    location,
 5687                    paths,
 5688                    center_group,
 5689                    window_bounds,
 5690                    display: Default::default(),
 5691                    docks,
 5692                    centered_layout: self.centered_layout,
 5693                    session_id: self.session_id.clone(),
 5694                    breakpoints,
 5695                    window_id: Some(window.window_handle().window_id().as_u64()),
 5696                    user_toolchains,
 5697                };
 5698
 5699                window.spawn(cx, async move |_| {
 5700                    persistence::DB.save_workspace(serialized_workspace).await;
 5701                })
 5702            }
 5703            WorkspaceLocation::DetachFromSession => {
 5704                let window_bounds = SerializedWindowBounds(window.window_bounds());
 5705                let display = window.display(cx).and_then(|d| d.uuid().ok());
 5706                window.spawn(cx, async move |_| {
 5707                    persistence::DB
 5708                        .set_window_open_status(
 5709                            database_id,
 5710                            window_bounds,
 5711                            display.unwrap_or_default(),
 5712                        )
 5713                        .await
 5714                        .log_err();
 5715                    persistence::DB
 5716                        .set_session_id(database_id, None)
 5717                        .await
 5718                        .log_err();
 5719                })
 5720            }
 5721            WorkspaceLocation::None => Task::ready(()),
 5722        }
 5723    }
 5724
 5725    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5726        let paths = PathList::new(&self.root_paths(cx));
 5727        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5728            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 5729        } else if self.project.read(cx).is_local() {
 5730            if !paths.is_empty() {
 5731                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5732            } else {
 5733                WorkspaceLocation::DetachFromSession
 5734            }
 5735        } else {
 5736            WorkspaceLocation::None
 5737        }
 5738    }
 5739
 5740    fn update_history(&self, cx: &mut App) {
 5741        let Some(id) = self.database_id() else {
 5742            return;
 5743        };
 5744        if !self.project.read(cx).is_local() {
 5745            return;
 5746        }
 5747        if let Some(manager) = HistoryManager::global(cx) {
 5748            let paths = PathList::new(&self.root_paths(cx));
 5749            manager.update(cx, |this, cx| {
 5750                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5751            });
 5752        }
 5753    }
 5754
 5755    async fn serialize_items(
 5756        this: &WeakEntity<Self>,
 5757        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5758        cx: &mut AsyncWindowContext,
 5759    ) -> Result<()> {
 5760        const CHUNK_SIZE: usize = 200;
 5761
 5762        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5763
 5764        while let Some(items_received) = serializable_items.next().await {
 5765            let unique_items =
 5766                items_received
 5767                    .into_iter()
 5768                    .fold(HashMap::default(), |mut acc, item| {
 5769                        acc.entry(item.item_id()).or_insert(item);
 5770                        acc
 5771                    });
 5772
 5773            // We use into_iter() here so that the references to the items are moved into
 5774            // the tasks and not kept alive while we're sleeping.
 5775            for (_, item) in unique_items.into_iter() {
 5776                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5777                    item.serialize(workspace, false, window, cx)
 5778                }) {
 5779                    cx.background_spawn(async move { task.await.log_err() })
 5780                        .detach();
 5781                }
 5782            }
 5783
 5784            cx.background_executor()
 5785                .timer(SERIALIZATION_THROTTLE_TIME)
 5786                .await;
 5787        }
 5788
 5789        Ok(())
 5790    }
 5791
 5792    pub(crate) fn enqueue_item_serialization(
 5793        &mut self,
 5794        item: Box<dyn SerializableItemHandle>,
 5795    ) -> Result<()> {
 5796        self.serializable_items_tx
 5797            .unbounded_send(item)
 5798            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5799    }
 5800
 5801    pub(crate) fn load_workspace(
 5802        serialized_workspace: SerializedWorkspace,
 5803        paths_to_open: Vec<Option<ProjectPath>>,
 5804        window: &mut Window,
 5805        cx: &mut Context<Workspace>,
 5806    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5807        cx.spawn_in(window, async move |workspace, cx| {
 5808            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5809
 5810            let mut center_group = None;
 5811            let mut center_items = None;
 5812
 5813            // Traverse the splits tree and add to things
 5814            if let Some((group, active_pane, items)) = serialized_workspace
 5815                .center_group
 5816                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5817                .await
 5818            {
 5819                center_items = Some(items);
 5820                center_group = Some((group, active_pane))
 5821            }
 5822
 5823            let mut items_by_project_path = HashMap::default();
 5824            let mut item_ids_by_kind = HashMap::default();
 5825            let mut all_deserialized_items = Vec::default();
 5826            cx.update(|_, cx| {
 5827                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5828                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5829                        item_ids_by_kind
 5830                            .entry(serializable_item_handle.serialized_item_kind())
 5831                            .or_insert(Vec::new())
 5832                            .push(item.item_id().as_u64() as ItemId);
 5833                    }
 5834
 5835                    if let Some(project_path) = item.project_path(cx) {
 5836                        items_by_project_path.insert(project_path, item.clone());
 5837                    }
 5838                    all_deserialized_items.push(item);
 5839                }
 5840            })?;
 5841
 5842            let opened_items = paths_to_open
 5843                .into_iter()
 5844                .map(|path_to_open| {
 5845                    path_to_open
 5846                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5847                })
 5848                .collect::<Vec<_>>();
 5849
 5850            // Remove old panes from workspace panes list
 5851            workspace.update_in(cx, |workspace, window, cx| {
 5852                if let Some((center_group, active_pane)) = center_group {
 5853                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5854
 5855                    // Swap workspace center group
 5856                    workspace.center = PaneGroup::with_root(center_group);
 5857                    workspace.center.set_is_center(true);
 5858                    workspace.center.mark_positions(cx);
 5859
 5860                    if let Some(active_pane) = active_pane {
 5861                        workspace.set_active_pane(&active_pane, window, cx);
 5862                        cx.focus_self(window);
 5863                    } else {
 5864                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5865                    }
 5866                }
 5867
 5868                let docks = serialized_workspace.docks;
 5869
 5870                for (dock, serialized_dock) in [
 5871                    (&mut workspace.right_dock, docks.right),
 5872                    (&mut workspace.left_dock, docks.left),
 5873                    (&mut workspace.bottom_dock, docks.bottom),
 5874                ]
 5875                .iter_mut()
 5876                {
 5877                    dock.update(cx, |dock, cx| {
 5878                        dock.serialized_dock = Some(serialized_dock.clone());
 5879                        dock.restore_state(window, cx);
 5880                    });
 5881                }
 5882
 5883                cx.notify();
 5884            })?;
 5885
 5886            let _ = project
 5887                .update(cx, |project, cx| {
 5888                    project
 5889                        .breakpoint_store()
 5890                        .update(cx, |breakpoint_store, cx| {
 5891                            breakpoint_store
 5892                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5893                        })
 5894                })?
 5895                .await;
 5896
 5897            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5898            // after loading the items, we might have different items and in order to avoid
 5899            // the database filling up, we delete items that haven't been loaded now.
 5900            //
 5901            // The items that have been loaded, have been saved after they've been added to the workspace.
 5902            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5903                item_ids_by_kind
 5904                    .into_iter()
 5905                    .map(|(item_kind, loaded_items)| {
 5906                        SerializableItemRegistry::cleanup(
 5907                            item_kind,
 5908                            serialized_workspace.id,
 5909                            loaded_items,
 5910                            window,
 5911                            cx,
 5912                        )
 5913                        .log_err()
 5914                    })
 5915                    .collect::<Vec<_>>()
 5916            })?;
 5917
 5918            futures::future::join_all(clean_up_tasks).await;
 5919
 5920            workspace
 5921                .update_in(cx, |workspace, window, cx| {
 5922                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5923                    workspace.serialize_workspace_internal(window, cx).detach();
 5924
 5925                    // Ensure that we mark the window as edited if we did load dirty items
 5926                    workspace.update_window_edited(window, cx);
 5927                })
 5928                .ok();
 5929
 5930            Ok(opened_items)
 5931        })
 5932    }
 5933
 5934    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5935        self.add_workspace_actions_listeners(div, window, cx)
 5936            .on_action(cx.listener(
 5937                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 5938                    for action in &action_sequence.0 {
 5939                        window.dispatch_action(action.boxed_clone(), cx);
 5940                    }
 5941                },
 5942            ))
 5943            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5944            .on_action(cx.listener(Self::close_all_items_and_panes))
 5945            .on_action(cx.listener(Self::save_all))
 5946            .on_action(cx.listener(Self::send_keystrokes))
 5947            .on_action(cx.listener(Self::add_folder_to_project))
 5948            .on_action(cx.listener(Self::follow_next_collaborator))
 5949            .on_action(cx.listener(Self::close_window))
 5950            .on_action(cx.listener(Self::activate_pane_at_index))
 5951            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5952            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5953            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 5954            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5955                let pane = workspace.active_pane().clone();
 5956                workspace.unfollow_in_pane(&pane, window, cx);
 5957            }))
 5958            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5959                workspace
 5960                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5961                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5962            }))
 5963            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5964                workspace
 5965                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5966                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5967            }))
 5968            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5969                workspace
 5970                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5971                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5972            }))
 5973            .on_action(
 5974                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5975                    workspace.activate_previous_pane(window, cx)
 5976                }),
 5977            )
 5978            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5979                workspace.activate_next_pane(window, cx)
 5980            }))
 5981            .on_action(
 5982                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5983                    workspace.activate_next_window(cx)
 5984                }),
 5985            )
 5986            .on_action(
 5987                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5988                    workspace.activate_previous_window(cx)
 5989                }),
 5990            )
 5991            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5992                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5993            }))
 5994            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5995                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5996            }))
 5997            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5998                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5999            }))
 6000            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6001                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6002            }))
 6003            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6004                workspace.activate_next_pane(window, cx)
 6005            }))
 6006            .on_action(cx.listener(
 6007                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6008                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6009                },
 6010            ))
 6011            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6012                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6013            }))
 6014            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6015                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6016            }))
 6017            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6018                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6019            }))
 6020            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6021                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6022            }))
 6023            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6024                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6025                    SplitDirection::Down,
 6026                    SplitDirection::Up,
 6027                    SplitDirection::Right,
 6028                    SplitDirection::Left,
 6029                ];
 6030                for dir in DIRECTION_PRIORITY {
 6031                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6032                        workspace.swap_pane_in_direction(dir, cx);
 6033                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6034                        break;
 6035                    }
 6036                }
 6037            }))
 6038            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6039                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6040            }))
 6041            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6042                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6043            }))
 6044            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6045                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6046            }))
 6047            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6048                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6049            }))
 6050            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6051                this.toggle_dock(DockPosition::Left, window, cx);
 6052            }))
 6053            .on_action(cx.listener(
 6054                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6055                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6056                },
 6057            ))
 6058            .on_action(cx.listener(
 6059                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6060                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6061                },
 6062            ))
 6063            .on_action(cx.listener(
 6064                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6065                    if !workspace.close_active_dock(window, cx) {
 6066                        cx.propagate();
 6067                    }
 6068                },
 6069            ))
 6070            .on_action(
 6071                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6072                    workspace.close_all_docks(window, cx);
 6073                }),
 6074            )
 6075            .on_action(cx.listener(Self::toggle_all_docks))
 6076            .on_action(cx.listener(
 6077                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6078                    workspace.clear_all_notifications(cx);
 6079                },
 6080            ))
 6081            .on_action(cx.listener(
 6082                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6083                    workspace.clear_navigation_history(window, cx);
 6084                },
 6085            ))
 6086            .on_action(cx.listener(
 6087                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6088                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6089                        workspace.suppress_notification(&notification_id, cx);
 6090                    }
 6091                },
 6092            ))
 6093            .on_action(cx.listener(
 6094                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6095                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6096                },
 6097            ))
 6098            .on_action(
 6099                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6100                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6101                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6102                            trusted_worktrees.clear_trusted_paths()
 6103                        });
 6104                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6105                        cx.spawn(async move |_, cx| {
 6106                            if clear_task.await.log_err().is_some() {
 6107                                cx.update(|cx| reload(cx)).ok();
 6108                            }
 6109                        })
 6110                        .detach();
 6111                    }
 6112                }),
 6113            )
 6114            .on_action(cx.listener(
 6115                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6116                    workspace.reopen_closed_item(window, cx).detach();
 6117                },
 6118            ))
 6119            .on_action(cx.listener(
 6120                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6121                    for dock in workspace.all_docks() {
 6122                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6123                            let Some(panel) = dock.read(cx).active_panel() else {
 6124                                return;
 6125                            };
 6126
 6127                            // Set to `None`, then the size will fall back to the default.
 6128                            panel.clone().set_size(None, window, cx);
 6129
 6130                            return;
 6131                        }
 6132                    }
 6133                },
 6134            ))
 6135            .on_action(cx.listener(
 6136                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6137                    for dock in workspace.all_docks() {
 6138                        if let Some(panel) = dock.read(cx).visible_panel() {
 6139                            // Set to `None`, then the size will fall back to the default.
 6140                            panel.clone().set_size(None, window, cx);
 6141                        }
 6142                    }
 6143                },
 6144            ))
 6145            .on_action(cx.listener(
 6146                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6147                    adjust_active_dock_size_by_px(
 6148                        px_with_ui_font_fallback(act.px, cx),
 6149                        workspace,
 6150                        window,
 6151                        cx,
 6152                    );
 6153                },
 6154            ))
 6155            .on_action(cx.listener(
 6156                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6157                    adjust_active_dock_size_by_px(
 6158                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6159                        workspace,
 6160                        window,
 6161                        cx,
 6162                    );
 6163                },
 6164            ))
 6165            .on_action(cx.listener(
 6166                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6167                    adjust_open_docks_size_by_px(
 6168                        px_with_ui_font_fallback(act.px, cx),
 6169                        workspace,
 6170                        window,
 6171                        cx,
 6172                    );
 6173                },
 6174            ))
 6175            .on_action(cx.listener(
 6176                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6177                    adjust_open_docks_size_by_px(
 6178                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6179                        workspace,
 6180                        window,
 6181                        cx,
 6182                    );
 6183                },
 6184            ))
 6185            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6186            .on_action(cx.listener(
 6187                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6188                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6189                        let dock = active_dock.read(cx);
 6190                        if let Some(active_panel) = dock.active_panel() {
 6191                            if active_panel.pane(cx).is_none() {
 6192                                let mut recent_pane: Option<Entity<Pane>> = None;
 6193                                let mut recent_timestamp = 0;
 6194                                for pane_handle in workspace.panes() {
 6195                                    let pane = pane_handle.read(cx);
 6196                                    for entry in pane.activation_history() {
 6197                                        if entry.timestamp > recent_timestamp {
 6198                                            recent_timestamp = entry.timestamp;
 6199                                            recent_pane = Some(pane_handle.clone());
 6200                                        }
 6201                                    }
 6202                                }
 6203
 6204                                if let Some(pane) = recent_pane {
 6205                                    pane.update(cx, |pane, cx| {
 6206                                        let current_index = pane.active_item_index();
 6207                                        let items_len = pane.items_len();
 6208                                        if items_len > 0 {
 6209                                            let next_index = if current_index + 1 < items_len {
 6210                                                current_index + 1
 6211                                            } else {
 6212                                                0
 6213                                            };
 6214                                            pane.activate_item(
 6215                                                next_index, false, false, window, cx,
 6216                                            );
 6217                                        }
 6218                                    });
 6219                                    return;
 6220                                }
 6221                            }
 6222                        }
 6223                    }
 6224                    cx.propagate();
 6225                },
 6226            ))
 6227            .on_action(cx.listener(
 6228                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6229                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6230                        let dock = active_dock.read(cx);
 6231                        if let Some(active_panel) = dock.active_panel() {
 6232                            if active_panel.pane(cx).is_none() {
 6233                                let mut recent_pane: Option<Entity<Pane>> = None;
 6234                                let mut recent_timestamp = 0;
 6235                                for pane_handle in workspace.panes() {
 6236                                    let pane = pane_handle.read(cx);
 6237                                    for entry in pane.activation_history() {
 6238                                        if entry.timestamp > recent_timestamp {
 6239                                            recent_timestamp = entry.timestamp;
 6240                                            recent_pane = Some(pane_handle.clone());
 6241                                        }
 6242                                    }
 6243                                }
 6244
 6245                                if let Some(pane) = recent_pane {
 6246                                    pane.update(cx, |pane, cx| {
 6247                                        let current_index = pane.active_item_index();
 6248                                        let items_len = pane.items_len();
 6249                                        if items_len > 0 {
 6250                                            let prev_index = if current_index > 0 {
 6251                                                current_index - 1
 6252                                            } else {
 6253                                                items_len.saturating_sub(1)
 6254                                            };
 6255                                            pane.activate_item(
 6256                                                prev_index, false, false, window, cx,
 6257                                            );
 6258                                        }
 6259                                    });
 6260                                    return;
 6261                                }
 6262                            }
 6263                        }
 6264                    }
 6265                    cx.propagate();
 6266                },
 6267            ))
 6268            .on_action(
 6269                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6270                    let pane = workspace.active_pane().clone();
 6271                    if let Some(item) = pane.read(cx).active_item() {
 6272                        item.toggle_read_only(window, cx);
 6273                    }
 6274                }),
 6275            )
 6276            .on_action(cx.listener(Workspace::cancel))
 6277    }
 6278
 6279    #[cfg(any(test, feature = "test-support"))]
 6280    pub fn set_random_database_id(&mut self) {
 6281        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6282    }
 6283
 6284    #[cfg(any(test, feature = "test-support"))]
 6285    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 6286        use node_runtime::NodeRuntime;
 6287        use session::Session;
 6288
 6289        let client = project.read(cx).client();
 6290        let user_store = project.read(cx).user_store();
 6291        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6292        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6293        window.activate_window();
 6294        let app_state = Arc::new(AppState {
 6295            languages: project.read(cx).languages().clone(),
 6296            workspace_store,
 6297            client,
 6298            user_store,
 6299            fs: project.read(cx).fs().clone(),
 6300            build_window_options: |_, _| Default::default(),
 6301            node_runtime: NodeRuntime::unavailable(),
 6302            session,
 6303        });
 6304        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6305        workspace
 6306            .active_pane
 6307            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6308        workspace
 6309    }
 6310
 6311    pub fn register_action<A: Action>(
 6312        &mut self,
 6313        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6314    ) -> &mut Self {
 6315        let callback = Arc::new(callback);
 6316
 6317        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6318            let callback = callback.clone();
 6319            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6320                (callback)(workspace, event, window, cx)
 6321            }))
 6322        }));
 6323        self
 6324    }
 6325    pub fn register_action_renderer(
 6326        &mut self,
 6327        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6328    ) -> &mut Self {
 6329        self.workspace_actions.push(Box::new(callback));
 6330        self
 6331    }
 6332
 6333    fn add_workspace_actions_listeners(
 6334        &self,
 6335        mut div: Div,
 6336        window: &mut Window,
 6337        cx: &mut Context<Self>,
 6338    ) -> Div {
 6339        for action in self.workspace_actions.iter() {
 6340            div = (action)(div, self, window, cx)
 6341        }
 6342        div
 6343    }
 6344
 6345    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6346        self.modal_layer.read(cx).has_active_modal()
 6347    }
 6348
 6349    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6350        self.modal_layer.read(cx).active_modal()
 6351    }
 6352
 6353    pub fn is_modal_open<V: 'static>(&self, cx: &App) -> bool {
 6354        self.modal_layer.read(cx).active_modal::<V>().is_some()
 6355    }
 6356
 6357    pub fn set_next_modal_placement(&mut self, placement: ModalPlacement) {
 6358        self.next_modal_placement = Some(placement);
 6359    }
 6360
 6361    fn take_next_modal_placement(&mut self) -> ModalPlacement {
 6362        self.next_modal_placement.take().unwrap_or_default()
 6363    }
 6364
 6365    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6366    where
 6367        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6368    {
 6369        let placement = self.take_next_modal_placement();
 6370        self.modal_layer.update(cx, |modal_layer, cx| {
 6371            modal_layer.toggle_modal_with_placement(window, cx, placement, build)
 6372        })
 6373    }
 6374
 6375    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6376        self.modal_layer
 6377            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6378    }
 6379
 6380    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6381        self.toast_layer
 6382            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6383    }
 6384
 6385    pub fn toggle_centered_layout(
 6386        &mut self,
 6387        _: &ToggleCenteredLayout,
 6388        _: &mut Window,
 6389        cx: &mut Context<Self>,
 6390    ) {
 6391        self.centered_layout = !self.centered_layout;
 6392        if let Some(database_id) = self.database_id() {
 6393            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6394                .detach_and_log_err(cx);
 6395        }
 6396        cx.notify();
 6397    }
 6398
 6399    fn adjust_padding(padding: Option<f32>) -> f32 {
 6400        padding
 6401            .unwrap_or(CenteredPaddingSettings::default().0)
 6402            .clamp(
 6403                CenteredPaddingSettings::MIN_PADDING,
 6404                CenteredPaddingSettings::MAX_PADDING,
 6405            )
 6406    }
 6407
 6408    fn render_dock(
 6409        &self,
 6410        position: DockPosition,
 6411        dock: &Entity<Dock>,
 6412        window: &mut Window,
 6413        cx: &mut App,
 6414    ) -> Option<Div> {
 6415        if self.zoomed_position == Some(position) {
 6416            return None;
 6417        }
 6418
 6419        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6420            let pane = panel.pane(cx)?;
 6421            let follower_states = &self.follower_states;
 6422            leader_border_for_pane(follower_states, &pane, window, cx)
 6423        });
 6424
 6425        Some(
 6426            div()
 6427                .flex()
 6428                .flex_none()
 6429                .overflow_hidden()
 6430                .child(dock.clone())
 6431                .children(leader_border),
 6432        )
 6433    }
 6434
 6435    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 6436        window.root().flatten()
 6437    }
 6438
 6439    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6440        self.zoomed.as_ref()
 6441    }
 6442
 6443    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6444        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6445            return;
 6446        };
 6447        let windows = cx.windows();
 6448        let next_window =
 6449            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6450                || {
 6451                    windows
 6452                        .iter()
 6453                        .cycle()
 6454                        .skip_while(|window| window.window_id() != current_window_id)
 6455                        .nth(1)
 6456                },
 6457            );
 6458
 6459        if let Some(window) = next_window {
 6460            window
 6461                .update(cx, |_, window, _| window.activate_window())
 6462                .ok();
 6463        }
 6464    }
 6465
 6466    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6467        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6468            return;
 6469        };
 6470        let windows = cx.windows();
 6471        let prev_window =
 6472            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6473                || {
 6474                    windows
 6475                        .iter()
 6476                        .rev()
 6477                        .cycle()
 6478                        .skip_while(|window| window.window_id() != current_window_id)
 6479                        .nth(1)
 6480                },
 6481            );
 6482
 6483        if let Some(window) = prev_window {
 6484            window
 6485                .update(cx, |_, window, _| window.activate_window())
 6486                .ok();
 6487        }
 6488    }
 6489
 6490    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6491        if cx.stop_active_drag(window) {
 6492        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6493            dismiss_app_notification(&notification_id, cx);
 6494        } else {
 6495            cx.propagate();
 6496        }
 6497    }
 6498
 6499    fn adjust_dock_size_by_px(
 6500        &mut self,
 6501        panel_size: Pixels,
 6502        dock_pos: DockPosition,
 6503        px: Pixels,
 6504        window: &mut Window,
 6505        cx: &mut Context<Self>,
 6506    ) {
 6507        match dock_pos {
 6508            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6509            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6510            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6511        }
 6512    }
 6513
 6514    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6515        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6516
 6517        self.left_dock.update(cx, |left_dock, cx| {
 6518            if WorkspaceSettings::get_global(cx)
 6519                .resize_all_panels_in_dock
 6520                .contains(&DockPosition::Left)
 6521            {
 6522                left_dock.resize_all_panels(Some(size), window, cx);
 6523            } else {
 6524                left_dock.resize_active_panel(Some(size), window, cx);
 6525            }
 6526        });
 6527        self.clamp_utility_pane_widths(window, cx);
 6528    }
 6529
 6530    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6531        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6532        self.left_dock.read_with(cx, |left_dock, cx| {
 6533            let left_dock_size = left_dock
 6534                .active_panel_size(window, cx)
 6535                .unwrap_or(Pixels::ZERO);
 6536            if left_dock_size + size > self.bounds.right() {
 6537                size = self.bounds.right() - left_dock_size
 6538            }
 6539        });
 6540        self.right_dock.update(cx, |right_dock, cx| {
 6541            if WorkspaceSettings::get_global(cx)
 6542                .resize_all_panels_in_dock
 6543                .contains(&DockPosition::Right)
 6544            {
 6545                right_dock.resize_all_panels(Some(size), window, cx);
 6546            } else {
 6547                right_dock.resize_active_panel(Some(size), window, cx);
 6548            }
 6549        });
 6550        self.clamp_utility_pane_widths(window, cx);
 6551    }
 6552
 6553    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6554        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6555        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6556            if WorkspaceSettings::get_global(cx)
 6557                .resize_all_panels_in_dock
 6558                .contains(&DockPosition::Bottom)
 6559            {
 6560                bottom_dock.resize_all_panels(Some(size), window, cx);
 6561            } else {
 6562                bottom_dock.resize_active_panel(Some(size), window, cx);
 6563            }
 6564        });
 6565        self.clamp_utility_pane_widths(window, cx);
 6566    }
 6567
 6568    fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
 6569        let left_dock_width = self
 6570            .left_dock
 6571            .read(cx)
 6572            .active_panel_size(window, cx)
 6573            .unwrap_or(px(0.0));
 6574        let right_dock_width = self
 6575            .right_dock
 6576            .read(cx)
 6577            .active_panel_size(window, cx)
 6578            .unwrap_or(px(0.0));
 6579        let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
 6580        center_pane_width - px(10.0)
 6581    }
 6582
 6583    fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
 6584        let max_width = self.max_utility_pane_width(window, cx);
 6585
 6586        // Clamp left slot utility pane if it exists
 6587        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
 6588            let current_width = handle.width(cx);
 6589            if current_width > max_width {
 6590                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6591            }
 6592        }
 6593
 6594        // Clamp right slot utility pane if it exists
 6595        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
 6596            let current_width = handle.width(cx);
 6597            if current_width > max_width {
 6598                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6599            }
 6600        }
 6601    }
 6602
 6603    fn toggle_edit_predictions_all_files(
 6604        &mut self,
 6605        _: &ToggleEditPrediction,
 6606        _window: &mut Window,
 6607        cx: &mut Context<Self>,
 6608    ) {
 6609        let fs = self.project().read(cx).fs().clone();
 6610        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6611        update_settings_file(fs, cx, move |file, _| {
 6612            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6613        });
 6614    }
 6615
 6616    pub fn show_worktree_trust_security_modal(
 6617        &mut self,
 6618        toggle: bool,
 6619        window: &mut Window,
 6620        cx: &mut Context<Self>,
 6621    ) {
 6622        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 6623            if toggle {
 6624                security_modal.update(cx, |security_modal, cx| {
 6625                    security_modal.dismiss(cx);
 6626                })
 6627            } else {
 6628                security_modal.update(cx, |security_modal, cx| {
 6629                    security_modal.refresh_restricted_paths(cx);
 6630                });
 6631            }
 6632        } else {
 6633            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 6634                .map(|trusted_worktrees| {
 6635                    trusted_worktrees
 6636                        .read(cx)
 6637                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 6638                })
 6639                .unwrap_or(false);
 6640            if has_restricted_worktrees {
 6641                let project = self.project().read(cx);
 6642                let remote_host = project
 6643                    .remote_connection_options(cx)
 6644                    .map(RemoteHostLocation::from);
 6645                let worktree_store = project.worktree_store().downgrade();
 6646                self.toggle_modal(window, cx, |_, cx| {
 6647                    SecurityModal::new(worktree_store, remote_host, cx)
 6648                });
 6649            }
 6650        }
 6651    }
 6652
 6653    fn update_worktree_data(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) {
 6654        self.update_window_title(window, cx);
 6655        self.serialize_workspace(window, cx);
 6656        // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
 6657        self.update_history(cx);
 6658    }
 6659}
 6660
 6661fn leader_border_for_pane(
 6662    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6663    pane: &Entity<Pane>,
 6664    _: &Window,
 6665    cx: &App,
 6666) -> Option<Div> {
 6667    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6668        if state.pane() == pane {
 6669            Some((*leader_id, state))
 6670        } else {
 6671            None
 6672        }
 6673    })?;
 6674
 6675    let mut leader_color = match leader_id {
 6676        CollaboratorId::PeerId(leader_peer_id) => {
 6677            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6678            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6679
 6680            cx.theme()
 6681                .players()
 6682                .color_for_participant(leader.participant_index.0)
 6683                .cursor
 6684        }
 6685        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6686    };
 6687    leader_color.fade_out(0.3);
 6688    Some(
 6689        div()
 6690            .absolute()
 6691            .size_full()
 6692            .left_0()
 6693            .top_0()
 6694            .border_2()
 6695            .border_color(leader_color),
 6696    )
 6697}
 6698
 6699fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 6700    ZED_WINDOW_POSITION
 6701        .zip(*ZED_WINDOW_SIZE)
 6702        .map(|(position, size)| Bounds {
 6703            origin: position,
 6704            size,
 6705        })
 6706}
 6707
 6708fn open_items(
 6709    serialized_workspace: Option<SerializedWorkspace>,
 6710    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 6711    window: &mut Window,
 6712    cx: &mut Context<Workspace>,
 6713) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 6714    let restored_items = serialized_workspace.map(|serialized_workspace| {
 6715        Workspace::load_workspace(
 6716            serialized_workspace,
 6717            project_paths_to_open
 6718                .iter()
 6719                .map(|(_, project_path)| project_path)
 6720                .cloned()
 6721                .collect(),
 6722            window,
 6723            cx,
 6724        )
 6725    });
 6726
 6727    cx.spawn_in(window, async move |workspace, cx| {
 6728        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 6729
 6730        if let Some(restored_items) = restored_items {
 6731            let restored_items = restored_items.await?;
 6732
 6733            let restored_project_paths = restored_items
 6734                .iter()
 6735                .filter_map(|item| {
 6736                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 6737                        .ok()
 6738                        .flatten()
 6739                })
 6740                .collect::<HashSet<_>>();
 6741
 6742            for restored_item in restored_items {
 6743                opened_items.push(restored_item.map(Ok));
 6744            }
 6745
 6746            project_paths_to_open
 6747                .iter_mut()
 6748                .for_each(|(_, project_path)| {
 6749                    if let Some(project_path_to_open) = project_path
 6750                        && restored_project_paths.contains(project_path_to_open)
 6751                    {
 6752                        *project_path = None;
 6753                    }
 6754                });
 6755        } else {
 6756            for _ in 0..project_paths_to_open.len() {
 6757                opened_items.push(None);
 6758            }
 6759        }
 6760        assert!(opened_items.len() == project_paths_to_open.len());
 6761
 6762        let tasks =
 6763            project_paths_to_open
 6764                .into_iter()
 6765                .enumerate()
 6766                .map(|(ix, (abs_path, project_path))| {
 6767                    let workspace = workspace.clone();
 6768                    cx.spawn(async move |cx| {
 6769                        let file_project_path = project_path?;
 6770                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6771                            workspace.project().update(cx, |project, cx| {
 6772                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6773                            })
 6774                        });
 6775
 6776                        // We only want to open file paths here. If one of the items
 6777                        // here is a directory, it was already opened further above
 6778                        // with a `find_or_create_worktree`.
 6779                        if let Ok(task) = abs_path_task
 6780                            && task.await.is_none_or(|p| p.is_file())
 6781                        {
 6782                            return Some((
 6783                                ix,
 6784                                workspace
 6785                                    .update_in(cx, |workspace, window, cx| {
 6786                                        workspace.open_path(
 6787                                            file_project_path,
 6788                                            None,
 6789                                            true,
 6790                                            window,
 6791                                            cx,
 6792                                        )
 6793                                    })
 6794                                    .log_err()?
 6795                                    .await,
 6796                            ));
 6797                        }
 6798                        None
 6799                    })
 6800                });
 6801
 6802        let tasks = tasks.collect::<Vec<_>>();
 6803
 6804        let tasks = futures::future::join_all(tasks);
 6805        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6806            opened_items[ix] = Some(path_open_result);
 6807        }
 6808
 6809        Ok(opened_items)
 6810    })
 6811}
 6812
 6813enum ActivateInDirectionTarget {
 6814    Pane(Entity<Pane>),
 6815    Dock(Entity<Dock>),
 6816}
 6817
 6818fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6819    workspace
 6820        .update(cx, |workspace, _, cx| {
 6821            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6822                struct DatabaseFailedNotification;
 6823
 6824                workspace.show_notification(
 6825                    NotificationId::unique::<DatabaseFailedNotification>(),
 6826                    cx,
 6827                    |cx| {
 6828                        cx.new(|cx| {
 6829                            MessageNotification::new("Failed to load the database file.", cx)
 6830                                .primary_message("File an Issue")
 6831                                .primary_icon(IconName::Plus)
 6832                                .primary_on_click(|window, cx| {
 6833                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6834                                })
 6835                        })
 6836                    },
 6837                );
 6838            }
 6839        })
 6840        .log_err();
 6841}
 6842
 6843fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6844    if val == 0 {
 6845        ThemeSettings::get_global(cx).ui_font_size(cx)
 6846    } else {
 6847        px(val as f32)
 6848    }
 6849}
 6850
 6851fn adjust_active_dock_size_by_px(
 6852    px: Pixels,
 6853    workspace: &mut Workspace,
 6854    window: &mut Window,
 6855    cx: &mut Context<Workspace>,
 6856) {
 6857    let Some(active_dock) = workspace
 6858        .all_docks()
 6859        .into_iter()
 6860        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6861    else {
 6862        return;
 6863    };
 6864    let dock = active_dock.read(cx);
 6865    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6866        return;
 6867    };
 6868    let dock_pos = dock.position();
 6869    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6870}
 6871
 6872fn adjust_open_docks_size_by_px(
 6873    px: Pixels,
 6874    workspace: &mut Workspace,
 6875    window: &mut Window,
 6876    cx: &mut Context<Workspace>,
 6877) {
 6878    let docks = workspace
 6879        .all_docks()
 6880        .into_iter()
 6881        .filter_map(|dock| {
 6882            if dock.read(cx).is_open() {
 6883                let dock = dock.read(cx);
 6884                let panel_size = dock.active_panel_size(window, cx)?;
 6885                let dock_pos = dock.position();
 6886                Some((panel_size, dock_pos, px))
 6887            } else {
 6888                None
 6889            }
 6890        })
 6891        .collect::<Vec<_>>();
 6892
 6893    docks
 6894        .into_iter()
 6895        .for_each(|(panel_size, dock_pos, offset)| {
 6896            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6897        });
 6898}
 6899
 6900impl Focusable for Workspace {
 6901    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6902        self.active_pane.focus_handle(cx)
 6903    }
 6904}
 6905
 6906#[derive(Clone)]
 6907struct DraggedDock(DockPosition);
 6908
 6909impl Render for DraggedDock {
 6910    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6911        gpui::Empty
 6912    }
 6913}
 6914
 6915impl Render for Workspace {
 6916    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6917        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 6918        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 6919            log::info!("Rendered first frame");
 6920        }
 6921        let mut context = KeyContext::new_with_defaults();
 6922        context.add("Workspace");
 6923        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6924        if let Some(status) = self
 6925            .debugger_provider
 6926            .as_ref()
 6927            .and_then(|provider| provider.active_thread_state(cx))
 6928        {
 6929            match status {
 6930                ThreadStatus::Running | ThreadStatus::Stepping => {
 6931                    context.add("debugger_running");
 6932                }
 6933                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6934                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6935            }
 6936        }
 6937
 6938        if self.left_dock.read(cx).is_open() {
 6939            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6940                context.set("left_dock", active_panel.panel_key());
 6941            }
 6942        }
 6943
 6944        if self.right_dock.read(cx).is_open() {
 6945            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6946                context.set("right_dock", active_panel.panel_key());
 6947            }
 6948        }
 6949
 6950        if self.bottom_dock.read(cx).is_open() {
 6951            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6952                context.set("bottom_dock", active_panel.panel_key());
 6953            }
 6954        }
 6955
 6956        let centered_layout = self.centered_layout
 6957            && self.center.panes().len() == 1
 6958            && self.active_item(cx).is_some();
 6959        let render_padding = |size| {
 6960            (size > 0.0).then(|| {
 6961                div()
 6962                    .h_full()
 6963                    .w(relative(size))
 6964                    .bg(cx.theme().colors().editor_background)
 6965                    .border_color(cx.theme().colors().pane_group_border)
 6966            })
 6967        };
 6968        let paddings = if centered_layout {
 6969            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6970            (
 6971                render_padding(Self::adjust_padding(
 6972                    settings.left_padding.map(|padding| padding.0),
 6973                )),
 6974                render_padding(Self::adjust_padding(
 6975                    settings.right_padding.map(|padding| padding.0),
 6976                )),
 6977            )
 6978        } else {
 6979            (None, None)
 6980        };
 6981        let ui_font = theme::setup_ui_font(window, cx);
 6982
 6983        let theme = cx.theme().clone();
 6984        let colors = theme.colors();
 6985        let notification_entities = self
 6986            .notifications
 6987            .iter()
 6988            .map(|(_, notification)| notification.entity_id())
 6989            .collect::<Vec<_>>();
 6990        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6991
 6992        client_side_decorations(
 6993            self.actions(div(), window, cx)
 6994                .key_context(context)
 6995                .relative()
 6996                .size_full()
 6997                .flex()
 6998                .flex_col()
 6999                .font(ui_font)
 7000                .gap_0()
 7001                .justify_start()
 7002                .items_start()
 7003                .text_color(colors.text)
 7004                .overflow_hidden()
 7005                .children(self.titlebar_item.clone())
 7006                .on_modifiers_changed(move |_, _, cx| {
 7007                    for &id in &notification_entities {
 7008                        cx.notify(id);
 7009                    }
 7010                })
 7011                .child(
 7012                    div()
 7013                        .size_full()
 7014                        .relative()
 7015                        .flex_1()
 7016                        .flex()
 7017                        .flex_col()
 7018                        .child(
 7019                            div()
 7020                                .id("workspace")
 7021                                .bg(colors.background)
 7022                                .relative()
 7023                                .flex_1()
 7024                                .w_full()
 7025                                .flex()
 7026                                .flex_col()
 7027                                .overflow_hidden()
 7028                                .border_t_1()
 7029                                .border_b_1()
 7030                                .border_color(colors.border)
 7031                                .child({
 7032                                    let this = cx.entity();
 7033                                    canvas(
 7034                                        move |bounds, window, cx| {
 7035                                            this.update(cx, |this, cx| {
 7036                                                let bounds_changed = this.bounds != bounds;
 7037                                                this.bounds = bounds;
 7038
 7039                                                if bounds_changed {
 7040                                                    this.left_dock.update(cx, |dock, cx| {
 7041                                                        dock.clamp_panel_size(
 7042                                                            bounds.size.width,
 7043                                                            window,
 7044                                                            cx,
 7045                                                        )
 7046                                                    });
 7047
 7048                                                    this.right_dock.update(cx, |dock, cx| {
 7049                                                        dock.clamp_panel_size(
 7050                                                            bounds.size.width,
 7051                                                            window,
 7052                                                            cx,
 7053                                                        )
 7054                                                    });
 7055
 7056                                                    this.bottom_dock.update(cx, |dock, cx| {
 7057                                                        dock.clamp_panel_size(
 7058                                                            bounds.size.height,
 7059                                                            window,
 7060                                                            cx,
 7061                                                        )
 7062                                                    });
 7063                                                }
 7064                                            })
 7065                                        },
 7066                                        |_, _, _, _| {},
 7067                                    )
 7068                                    .absolute()
 7069                                    .size_full()
 7070                                })
 7071                                .when(self.zoomed.is_none(), |this| {
 7072                                    this.on_drag_move(cx.listener(
 7073                                        move |workspace,
 7074                                              e: &DragMoveEvent<DraggedDock>,
 7075                                              window,
 7076                                              cx| {
 7077                                            if workspace.previous_dock_drag_coordinates
 7078                                                != Some(e.event.position)
 7079                                            {
 7080                                                workspace.previous_dock_drag_coordinates =
 7081                                                    Some(e.event.position);
 7082                                                match e.drag(cx).0 {
 7083                                                    DockPosition::Left => {
 7084                                                        workspace.resize_left_dock(
 7085                                                            e.event.position.x
 7086                                                                - workspace.bounds.left(),
 7087                                                            window,
 7088                                                            cx,
 7089                                                        );
 7090                                                    }
 7091                                                    DockPosition::Right => {
 7092                                                        workspace.resize_right_dock(
 7093                                                            workspace.bounds.right()
 7094                                                                - e.event.position.x,
 7095                                                            window,
 7096                                                            cx,
 7097                                                        );
 7098                                                    }
 7099                                                    DockPosition::Bottom => {
 7100                                                        workspace.resize_bottom_dock(
 7101                                                            workspace.bounds.bottom()
 7102                                                                - e.event.position.y,
 7103                                                            window,
 7104                                                            cx,
 7105                                                        );
 7106                                                    }
 7107                                                };
 7108                                                workspace.serialize_workspace(window, cx);
 7109                                            }
 7110                                        },
 7111                                    ))
 7112                                    .on_drag_move(cx.listener(
 7113                                        move |workspace,
 7114                                              e: &DragMoveEvent<DraggedUtilityPane>,
 7115                                              window,
 7116                                              cx| {
 7117                                            let slot = e.drag(cx).0;
 7118                                            match slot {
 7119                                                UtilityPaneSlot::Left => {
 7120                                                    let left_dock_width = workspace.left_dock.read(cx)
 7121                                                        .active_panel_size(window, cx)
 7122                                                        .unwrap_or(gpui::px(0.0));
 7123                                                    let new_width = e.event.position.x
 7124                                                        - workspace.bounds.left()
 7125                                                        - left_dock_width;
 7126                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7127                                                }
 7128                                                UtilityPaneSlot::Right => {
 7129                                                    let right_dock_width = workspace.right_dock.read(cx)
 7130                                                        .active_panel_size(window, cx)
 7131                                                        .unwrap_or(gpui::px(0.0));
 7132                                                    let new_width = workspace.bounds.right()
 7133                                                        - e.event.position.x
 7134                                                        - right_dock_width;
 7135                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7136                                                }
 7137                                            }
 7138                                        },
 7139                                    ))
 7140                                })
 7141                                .child({
 7142                                    match bottom_dock_layout {
 7143                                        BottomDockLayout::Full => div()
 7144                                            .flex()
 7145                                            .flex_col()
 7146                                            .h_full()
 7147                                            .child(
 7148                                                div()
 7149                                                    .flex()
 7150                                                    .flex_row()
 7151                                                    .flex_1()
 7152                                                    .overflow_hidden()
 7153                                                    .children(self.render_dock(
 7154                                                        DockPosition::Left,
 7155                                                        &self.left_dock,
 7156                                                        window,
 7157                                                        cx,
 7158                                                    ))
 7159                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7160                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7161                                                            this.when(pane.expanded(cx), |this| {
 7162                                                                this.child(
 7163                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7164                                                                )
 7165                                                            })
 7166                                                        })
 7167                                                    })
 7168                                                    .child(
 7169                                                        div()
 7170                                                            .flex()
 7171                                                            .flex_col()
 7172                                                            .flex_1()
 7173                                                            .overflow_hidden()
 7174                                                            .child(
 7175                                                                h_flex()
 7176                                                                    .flex_1()
 7177                                                                    .when_some(
 7178                                                                        paddings.0,
 7179                                                                        |this, p| {
 7180                                                                            this.child(
 7181                                                                                p.border_r_1(),
 7182                                                                            )
 7183                                                                        },
 7184                                                                    )
 7185                                                                    .child(self.center.render(
 7186                                                                        self.zoomed.as_ref(),
 7187                                                                        &PaneRenderContext {
 7188                                                                            follower_states:
 7189                                                                                &self.follower_states,
 7190                                                                            active_call: self.active_call(),
 7191                                                                            active_pane: &self.active_pane,
 7192                                                                            app_state: &self.app_state,
 7193                                                                            project: &self.project,
 7194                                                                            workspace: &self.weak_self,
 7195                                                                        },
 7196                                                                        window,
 7197                                                                        cx,
 7198                                                                    ))
 7199                                                                    .when_some(
 7200                                                                        paddings.1,
 7201                                                                        |this, p| {
 7202                                                                            this.child(
 7203                                                                                p.border_l_1(),
 7204                                                                            )
 7205                                                                        },
 7206                                                                    ),
 7207                                                            ),
 7208                                                    )
 7209                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7210                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7211                                                            this.when(pane.expanded(cx), |this| {
 7212                                                                this.child(
 7213                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7214                                                                )
 7215                                                            })
 7216                                                        })
 7217                                                    })
 7218                                                    .children(self.render_dock(
 7219                                                        DockPosition::Right,
 7220                                                        &self.right_dock,
 7221                                                        window,
 7222                                                        cx,
 7223                                                    )),
 7224                                            )
 7225                                            .child(div().w_full().children(self.render_dock(
 7226                                                DockPosition::Bottom,
 7227                                                &self.bottom_dock,
 7228                                                window,
 7229                                                cx
 7230                                            ))),
 7231
 7232                                        BottomDockLayout::LeftAligned => div()
 7233                                            .flex()
 7234                                            .flex_row()
 7235                                            .h_full()
 7236                                            .child(
 7237                                                div()
 7238                                                    .flex()
 7239                                                    .flex_col()
 7240                                                    .flex_1()
 7241                                                    .h_full()
 7242                                                    .child(
 7243                                                        div()
 7244                                                            .flex()
 7245                                                            .flex_row()
 7246                                                            .flex_1()
 7247                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7248                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7249                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7250                                                                    this.when(pane.expanded(cx), |this| {
 7251                                                                        this.child(
 7252                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7253                                                                        )
 7254                                                                    })
 7255                                                                })
 7256                                                            })
 7257                                                            .child(
 7258                                                                div()
 7259                                                                    .flex()
 7260                                                                    .flex_col()
 7261                                                                    .flex_1()
 7262                                                                    .overflow_hidden()
 7263                                                                    .child(
 7264                                                                        h_flex()
 7265                                                                            .flex_1()
 7266                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7267                                                                            .child(self.center.render(
 7268                                                                                self.zoomed.as_ref(),
 7269                                                                                &PaneRenderContext {
 7270                                                                                    follower_states:
 7271                                                                                        &self.follower_states,
 7272                                                                                    active_call: self.active_call(),
 7273                                                                                    active_pane: &self.active_pane,
 7274                                                                                    app_state: &self.app_state,
 7275                                                                                    project: &self.project,
 7276                                                                                    workspace: &self.weak_self,
 7277                                                                                },
 7278                                                                                window,
 7279                                                                                cx,
 7280                                                                            ))
 7281                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7282                                                                    )
 7283                                                            )
 7284                                                            .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7285                                                                this.when(pane.expanded(cx), |this| {
 7286                                                                    this.child(
 7287                                                                        UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7288                                                                    )
 7289                                                                })
 7290                                                            })
 7291                                                    )
 7292                                                    .child(
 7293                                                        div()
 7294                                                            .w_full()
 7295                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7296                                                    ),
 7297                                            )
 7298                                            .children(self.render_dock(
 7299                                                DockPosition::Right,
 7300                                                &self.right_dock,
 7301                                                window,
 7302                                                cx,
 7303                                            )),
 7304
 7305                                        BottomDockLayout::RightAligned => div()
 7306                                            .flex()
 7307                                            .flex_row()
 7308                                            .h_full()
 7309                                            .children(self.render_dock(
 7310                                                DockPosition::Left,
 7311                                                &self.left_dock,
 7312                                                window,
 7313                                                cx,
 7314                                            ))
 7315                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7316                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7317                                                    this.when(pane.expanded(cx), |this| {
 7318                                                        this.child(
 7319                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7320                                                        )
 7321                                                    })
 7322                                                })
 7323                                            })
 7324                                            .child(
 7325                                                div()
 7326                                                    .flex()
 7327                                                    .flex_col()
 7328                                                    .flex_1()
 7329                                                    .h_full()
 7330                                                    .child(
 7331                                                        div()
 7332                                                            .flex()
 7333                                                            .flex_row()
 7334                                                            .flex_1()
 7335                                                            .child(
 7336                                                                div()
 7337                                                                    .flex()
 7338                                                                    .flex_col()
 7339                                                                    .flex_1()
 7340                                                                    .overflow_hidden()
 7341                                                                    .child(
 7342                                                                        h_flex()
 7343                                                                            .flex_1()
 7344                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7345                                                                            .child(self.center.render(
 7346                                                                                self.zoomed.as_ref(),
 7347                                                                                &PaneRenderContext {
 7348                                                                                    follower_states:
 7349                                                                                        &self.follower_states,
 7350                                                                                    active_call: self.active_call(),
 7351                                                                                    active_pane: &self.active_pane,
 7352                                                                                    app_state: &self.app_state,
 7353                                                                                    project: &self.project,
 7354                                                                                    workspace: &self.weak_self,
 7355                                                                                },
 7356                                                                                window,
 7357                                                                                cx,
 7358                                                                            ))
 7359                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7360                                                                    )
 7361                                                            )
 7362                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7363                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7364                                                                    this.when(pane.expanded(cx), |this| {
 7365                                                                        this.child(
 7366                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7367                                                                        )
 7368                                                                    })
 7369                                                                })
 7370                                                            })
 7371                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7372                                                    )
 7373                                                    .child(
 7374                                                        div()
 7375                                                            .w_full()
 7376                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7377                                                    ),
 7378                                            ),
 7379
 7380                                        BottomDockLayout::Contained => div()
 7381                                            .flex()
 7382                                            .flex_row()
 7383                                            .h_full()
 7384                                            .children(self.render_dock(
 7385                                                DockPosition::Left,
 7386                                                &self.left_dock,
 7387                                                window,
 7388                                                cx,
 7389                                            ))
 7390                                            .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7391                                                this.when(pane.expanded(cx), |this| {
 7392                                                    this.child(
 7393                                                        UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7394                                                    )
 7395                                                })
 7396                                            })
 7397                                            .child(
 7398                                                div()
 7399                                                    .flex()
 7400                                                    .flex_col()
 7401                                                    .flex_1()
 7402                                                    .overflow_hidden()
 7403                                                    .child(
 7404                                                        h_flex()
 7405                                                            .flex_1()
 7406                                                            .when_some(paddings.0, |this, p| {
 7407                                                                this.child(p.border_r_1())
 7408                                                            })
 7409                                                            .child(self.center.render(
 7410                                                                self.zoomed.as_ref(),
 7411                                                                &PaneRenderContext {
 7412                                                                    follower_states:
 7413                                                                        &self.follower_states,
 7414                                                                    active_call: self.active_call(),
 7415                                                                    active_pane: &self.active_pane,
 7416                                                                    app_state: &self.app_state,
 7417                                                                    project: &self.project,
 7418                                                                    workspace: &self.weak_self,
 7419                                                                },
 7420                                                                window,
 7421                                                                cx,
 7422                                                            ))
 7423                                                            .when_some(paddings.1, |this, p| {
 7424                                                                this.child(p.border_l_1())
 7425                                                            }),
 7426                                                    )
 7427                                                    .children(self.render_dock(
 7428                                                        DockPosition::Bottom,
 7429                                                        &self.bottom_dock,
 7430                                                        window,
 7431                                                        cx,
 7432                                                    )),
 7433                                            )
 7434                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7435                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7436                                                    this.when(pane.expanded(cx), |this| {
 7437                                                        this.child(
 7438                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7439                                                        )
 7440                                                    })
 7441                                                })
 7442                                            })
 7443                                            .children(self.render_dock(
 7444                                                DockPosition::Right,
 7445                                                &self.right_dock,
 7446                                                window,
 7447                                                cx,
 7448                                            )),
 7449                                    }
 7450                                })
 7451                                .children(self.zoomed.as_ref().and_then(|view| {
 7452                                    let zoomed_view = view.upgrade()?;
 7453                                    let div = div()
 7454                                        .occlude()
 7455                                        .absolute()
 7456                                        .overflow_hidden()
 7457                                        .border_color(colors.border)
 7458                                        .bg(colors.background)
 7459                                        .child(zoomed_view)
 7460                                        .inset_0()
 7461                                        .shadow_lg();
 7462
 7463                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7464                                       return Some(div);
 7465                                    }
 7466
 7467                                    Some(match self.zoomed_position {
 7468                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7469                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7470                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7471                                        None => {
 7472                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7473                                        }
 7474                                    })
 7475                                }))
 7476                                .children(self.render_notifications(window, cx)),
 7477                        )
 7478                        .when(self.status_bar_visible(cx), |parent| {
 7479                            parent.child(self.status_bar.clone())
 7480                        })
 7481                        .child(self.modal_layer.clone())
 7482                        .child(self.toast_layer.clone()),
 7483                ),
 7484            window,
 7485            cx,
 7486        )
 7487    }
 7488}
 7489
 7490impl WorkspaceStore {
 7491    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7492        Self {
 7493            workspaces: Default::default(),
 7494            _subscriptions: vec![
 7495                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7496                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7497            ],
 7498            client,
 7499        }
 7500    }
 7501
 7502    pub fn update_followers(
 7503        &self,
 7504        project_id: Option<u64>,
 7505        update: proto::update_followers::Variant,
 7506        cx: &App,
 7507    ) -> Option<()> {
 7508        let active_call = ActiveCall::try_global(cx)?;
 7509        let room_id = active_call.read(cx).room()?.read(cx).id();
 7510        self.client
 7511            .send(proto::UpdateFollowers {
 7512                room_id,
 7513                project_id,
 7514                variant: Some(update),
 7515            })
 7516            .log_err()
 7517    }
 7518
 7519    pub async fn handle_follow(
 7520        this: Entity<Self>,
 7521        envelope: TypedEnvelope<proto::Follow>,
 7522        mut cx: AsyncApp,
 7523    ) -> Result<proto::FollowResponse> {
 7524        this.update(&mut cx, |this, cx| {
 7525            let follower = Follower {
 7526                project_id: envelope.payload.project_id,
 7527                peer_id: envelope.original_sender_id()?,
 7528            };
 7529
 7530            let mut response = proto::FollowResponse::default();
 7531            this.workspaces.retain(|workspace| {
 7532                workspace
 7533                    .update(cx, |workspace, window, cx| {
 7534                        let handler_response =
 7535                            workspace.handle_follow(follower.project_id, window, cx);
 7536                        if let Some(active_view) = handler_response.active_view
 7537                            && workspace.project.read(cx).remote_id() == follower.project_id
 7538                        {
 7539                            response.active_view = Some(active_view)
 7540                        }
 7541                    })
 7542                    .is_ok()
 7543            });
 7544
 7545            Ok(response)
 7546        })?
 7547    }
 7548
 7549    async fn handle_update_followers(
 7550        this: Entity<Self>,
 7551        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7552        mut cx: AsyncApp,
 7553    ) -> Result<()> {
 7554        let leader_id = envelope.original_sender_id()?;
 7555        let update = envelope.payload;
 7556
 7557        this.update(&mut cx, |this, cx| {
 7558            this.workspaces.retain(|workspace| {
 7559                workspace
 7560                    .update(cx, |workspace, window, cx| {
 7561                        let project_id = workspace.project.read(cx).remote_id();
 7562                        if update.project_id != project_id && update.project_id.is_some() {
 7563                            return;
 7564                        }
 7565                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 7566                    })
 7567                    .is_ok()
 7568            });
 7569            Ok(())
 7570        })?
 7571    }
 7572
 7573    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 7574        &self.workspaces
 7575    }
 7576}
 7577
 7578impl ViewId {
 7579    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7580        Ok(Self {
 7581            creator: message
 7582                .creator
 7583                .map(CollaboratorId::PeerId)
 7584                .context("creator is missing")?,
 7585            id: message.id,
 7586        })
 7587    }
 7588
 7589    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7590        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7591            Some(proto::ViewId {
 7592                creator: Some(peer_id),
 7593                id: self.id,
 7594            })
 7595        } else {
 7596            None
 7597        }
 7598    }
 7599}
 7600
 7601impl FollowerState {
 7602    fn pane(&self) -> &Entity<Pane> {
 7603        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 7604    }
 7605}
 7606
 7607pub trait WorkspaceHandle {
 7608    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 7609}
 7610
 7611impl WorkspaceHandle for Entity<Workspace> {
 7612    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 7613        self.read(cx)
 7614            .worktrees(cx)
 7615            .flat_map(|worktree| {
 7616                let worktree_id = worktree.read(cx).id();
 7617                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 7618                    worktree_id,
 7619                    path: f.path.clone(),
 7620                })
 7621            })
 7622            .collect::<Vec<_>>()
 7623    }
 7624}
 7625
 7626pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 7627    DB.last_workspace().await.log_err().flatten()
 7628}
 7629
 7630pub fn last_session_workspace_locations(
 7631    last_session_id: &str,
 7632    last_session_window_stack: Option<Vec<WindowId>>,
 7633) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 7634    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 7635        .log_err()
 7636}
 7637
 7638actions!(
 7639    collab,
 7640    [
 7641        /// Opens the channel notes for the current call.
 7642        ///
 7643        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 7644        /// channel in the collab panel.
 7645        ///
 7646        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 7647        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7648        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7649        OpenChannelNotes,
 7650        /// Mutes your microphone.
 7651        Mute,
 7652        /// Deafens yourself (mute both microphone and speakers).
 7653        Deafen,
 7654        /// Leaves the current call.
 7655        LeaveCall,
 7656        /// Shares the current project with collaborators.
 7657        ShareProject,
 7658        /// Shares your screen with collaborators.
 7659        ScreenShare,
 7660        /// Copies the current room name and session id for debugging purposes.
 7661        CopyRoomId,
 7662    ]
 7663);
 7664actions!(
 7665    zed,
 7666    [
 7667        /// Opens the Zed log file.
 7668        OpenLog,
 7669        /// Reveals the Zed log file in the system file manager.
 7670        RevealLogInFileManager
 7671    ]
 7672);
 7673
 7674async fn join_channel_internal(
 7675    channel_id: ChannelId,
 7676    app_state: &Arc<AppState>,
 7677    requesting_window: Option<WindowHandle<Workspace>>,
 7678    active_call: &Entity<ActiveCall>,
 7679    cx: &mut AsyncApp,
 7680) -> Result<bool> {
 7681    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7682        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7683            return (false, None);
 7684        };
 7685
 7686        let already_in_channel = room.channel_id() == Some(channel_id);
 7687        let should_prompt = room.is_sharing_project()
 7688            && !room.remote_participants().is_empty()
 7689            && !already_in_channel;
 7690        let open_room = if already_in_channel {
 7691            active_call.room().cloned()
 7692        } else {
 7693            None
 7694        };
 7695        (should_prompt, open_room)
 7696    })?;
 7697
 7698    if let Some(room) = open_room {
 7699        let task = room.update(cx, |room, cx| {
 7700            if let Some((project, host)) = room.most_active_project(cx) {
 7701                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7702            }
 7703
 7704            None
 7705        })?;
 7706        if let Some(task) = task {
 7707            task.await?;
 7708        }
 7709        return anyhow::Ok(true);
 7710    }
 7711
 7712    if should_prompt {
 7713        if let Some(workspace) = requesting_window {
 7714            let answer = workspace
 7715                .update(cx, |_, window, cx| {
 7716                    window.prompt(
 7717                        PromptLevel::Warning,
 7718                        "Do you want to switch channels?",
 7719                        Some("Leaving this call will unshare your current project."),
 7720                        &["Yes, Join Channel", "Cancel"],
 7721                        cx,
 7722                    )
 7723                })?
 7724                .await;
 7725
 7726            if answer == Ok(1) {
 7727                return Ok(false);
 7728            }
 7729        } else {
 7730            return Ok(false); // unreachable!() hopefully
 7731        }
 7732    }
 7733
 7734    let client = cx.update(|cx| active_call.read(cx).client())?;
 7735
 7736    let mut client_status = client.status();
 7737
 7738    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7739    'outer: loop {
 7740        let Some(status) = client_status.recv().await else {
 7741            anyhow::bail!("error connecting");
 7742        };
 7743
 7744        match status {
 7745            Status::Connecting
 7746            | Status::Authenticating
 7747            | Status::Authenticated
 7748            | Status::Reconnecting
 7749            | Status::Reauthenticating
 7750            | Status::Reauthenticated => continue,
 7751            Status::Connected { .. } => break 'outer,
 7752            Status::SignedOut | Status::AuthenticationError => {
 7753                return Err(ErrorCode::SignedOut.into());
 7754            }
 7755            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7756            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7757                return Err(ErrorCode::Disconnected.into());
 7758            }
 7759        }
 7760    }
 7761
 7762    let room = active_call
 7763        .update(cx, |active_call, cx| {
 7764            active_call.join_channel(channel_id, cx)
 7765        })?
 7766        .await?;
 7767
 7768    let Some(room) = room else {
 7769        return anyhow::Ok(true);
 7770    };
 7771
 7772    room.update(cx, |room, _| room.room_update_completed())?
 7773        .await;
 7774
 7775    let task = room.update(cx, |room, cx| {
 7776        if let Some((project, host)) = room.most_active_project(cx) {
 7777            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7778        }
 7779
 7780        // If you are the first to join a channel, see if you should share your project.
 7781        if room.remote_participants().is_empty()
 7782            && !room.local_participant_is_guest()
 7783            && let Some(workspace) = requesting_window
 7784        {
 7785            let project = workspace.update(cx, |workspace, _, cx| {
 7786                let project = workspace.project.read(cx);
 7787
 7788                if !CallSettings::get_global(cx).share_on_join {
 7789                    return None;
 7790                }
 7791
 7792                if (project.is_local() || project.is_via_remote_server())
 7793                    && project.visible_worktrees(cx).any(|tree| {
 7794                        tree.read(cx)
 7795                            .root_entry()
 7796                            .is_some_and(|entry| entry.is_dir())
 7797                    })
 7798                {
 7799                    Some(workspace.project.clone())
 7800                } else {
 7801                    None
 7802                }
 7803            });
 7804            if let Ok(Some(project)) = project {
 7805                return Some(cx.spawn(async move |room, cx| {
 7806                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7807                        .await?;
 7808                    Ok(())
 7809                }));
 7810            }
 7811        }
 7812
 7813        None
 7814    })?;
 7815    if let Some(task) = task {
 7816        task.await?;
 7817        return anyhow::Ok(true);
 7818    }
 7819    anyhow::Ok(false)
 7820}
 7821
 7822pub fn join_channel(
 7823    channel_id: ChannelId,
 7824    app_state: Arc<AppState>,
 7825    requesting_window: Option<WindowHandle<Workspace>>,
 7826    cx: &mut App,
 7827) -> Task<Result<()>> {
 7828    let active_call = ActiveCall::global(cx);
 7829    cx.spawn(async move |cx| {
 7830        let result =
 7831            join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
 7832                .await;
 7833
 7834        // join channel succeeded, and opened a window
 7835        if matches!(result, Ok(true)) {
 7836            return anyhow::Ok(());
 7837        }
 7838
 7839        // find an existing workspace to focus and show call controls
 7840        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 7841        if active_window.is_none() {
 7842            // no open workspaces, make one to show the error in (blergh)
 7843            let (window_handle, _) = cx
 7844                .update(|cx| {
 7845                    Workspace::new_local(
 7846                        vec![],
 7847                        app_state.clone(),
 7848                        requesting_window,
 7849                        None,
 7850                        None,
 7851                        cx,
 7852                    )
 7853                })?
 7854                .await?;
 7855
 7856            if result.is_ok() {
 7857                cx.update(|cx| {
 7858                    cx.dispatch_action(&OpenChannelNotes);
 7859                })
 7860                .log_err();
 7861            }
 7862
 7863            active_window = Some(window_handle);
 7864        }
 7865
 7866        if let Err(err) = result {
 7867            log::error!("failed to join channel: {}", err);
 7868            if let Some(active_window) = active_window {
 7869                active_window
 7870                    .update(cx, |_, window, cx| {
 7871                        let detail: SharedString = match err.error_code() {
 7872                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 7873                            ErrorCode::UpgradeRequired => concat!(
 7874                                "Your are running an unsupported version of Zed. ",
 7875                                "Please update to continue."
 7876                            )
 7877                            .into(),
 7878                            ErrorCode::NoSuchChannel => concat!(
 7879                                "No matching channel was found. ",
 7880                                "Please check the link and try again."
 7881                            )
 7882                            .into(),
 7883                            ErrorCode::Forbidden => concat!(
 7884                                "This channel is private, and you do not have access. ",
 7885                                "Please ask someone to add you and try again."
 7886                            )
 7887                            .into(),
 7888                            ErrorCode::Disconnected => {
 7889                                "Please check your internet connection and try again.".into()
 7890                            }
 7891                            _ => format!("{}\n\nPlease try again.", err).into(),
 7892                        };
 7893                        window.prompt(
 7894                            PromptLevel::Critical,
 7895                            "Failed to join channel",
 7896                            Some(&detail),
 7897                            &["Ok"],
 7898                            cx,
 7899                        )
 7900                    })?
 7901                    .await
 7902                    .ok();
 7903            }
 7904        }
 7905
 7906        // return ok, we showed the error to the user.
 7907        anyhow::Ok(())
 7908    })
 7909}
 7910
 7911pub async fn get_any_active_workspace(
 7912    app_state: Arc<AppState>,
 7913    mut cx: AsyncApp,
 7914) -> anyhow::Result<WindowHandle<Workspace>> {
 7915    // find an existing workspace to focus and show call controls
 7916    let active_window = activate_any_workspace_window(&mut cx);
 7917    if active_window.is_none() {
 7918        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))?
 7919            .await?;
 7920    }
 7921    activate_any_workspace_window(&mut cx).context("could not open zed")
 7922}
 7923
 7924fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7925    cx.update(|cx| {
 7926        if let Some(workspace_window) = cx
 7927            .active_window()
 7928            .and_then(|window| window.downcast::<Workspace>())
 7929        {
 7930            return Some(workspace_window);
 7931        }
 7932
 7933        for window in cx.windows() {
 7934            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7935                workspace_window
 7936                    .update(cx, |_, window, _| window.activate_window())
 7937                    .ok();
 7938                return Some(workspace_window);
 7939            }
 7940        }
 7941        None
 7942    })
 7943    .ok()
 7944    .flatten()
 7945}
 7946
 7947pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7948    cx.windows()
 7949        .into_iter()
 7950        .filter_map(|window| window.downcast::<Workspace>())
 7951        .filter(|workspace| {
 7952            workspace
 7953                .read(cx)
 7954                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7955        })
 7956        .collect()
 7957}
 7958
 7959#[derive(Default)]
 7960pub struct OpenOptions {
 7961    pub visible: Option<OpenVisible>,
 7962    pub focus: Option<bool>,
 7963    pub open_new_workspace: Option<bool>,
 7964    pub prefer_focused_window: bool,
 7965    pub replace_window: Option<WindowHandle<Workspace>>,
 7966    pub env: Option<HashMap<String, String>>,
 7967}
 7968
 7969#[allow(clippy::type_complexity)]
 7970pub fn open_paths(
 7971    abs_paths: &[PathBuf],
 7972    app_state: Arc<AppState>,
 7973    open_options: OpenOptions,
 7974    cx: &mut App,
 7975) -> Task<
 7976    anyhow::Result<(
 7977        WindowHandle<Workspace>,
 7978        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7979    )>,
 7980> {
 7981    let abs_paths = abs_paths.to_vec();
 7982    let mut existing = None;
 7983    let mut best_match = None;
 7984    let mut open_visible = OpenVisible::All;
 7985    #[cfg(target_os = "windows")]
 7986    let wsl_path = abs_paths
 7987        .iter()
 7988        .find_map(|p| util::paths::WslPath::from_path(p));
 7989
 7990    cx.spawn(async move |cx| {
 7991        if open_options.open_new_workspace != Some(true) {
 7992            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7993            let all_metadatas = futures::future::join_all(all_paths)
 7994                .await
 7995                .into_iter()
 7996                .filter_map(|result| result.ok().flatten())
 7997                .collect::<Vec<_>>();
 7998
 7999            cx.update(|cx| {
 8000                for window in local_workspace_windows(cx) {
 8001                    if let Ok(workspace) = window.read(cx) {
 8002                        let m = workspace.project.read(cx).visibility_for_paths(
 8003                            &abs_paths,
 8004                            &all_metadatas,
 8005                            open_options.open_new_workspace == None,
 8006                            cx,
 8007                        );
 8008                        if m > best_match {
 8009                            existing = Some(window);
 8010                            best_match = m;
 8011                        } else if best_match.is_none()
 8012                            && open_options.open_new_workspace == Some(false)
 8013                        {
 8014                            existing = Some(window)
 8015                        }
 8016                    }
 8017                }
 8018            })?;
 8019
 8020            if open_options.open_new_workspace.is_none()
 8021                && (existing.is_none() || open_options.prefer_focused_window)
 8022                && all_metadatas.iter().all(|file| !file.is_dir)
 8023            {
 8024                cx.update(|cx| {
 8025                    if let Some(window) = cx
 8026                        .active_window()
 8027                        .and_then(|window| window.downcast::<Workspace>())
 8028                        && let Ok(workspace) = window.read(cx)
 8029                    {
 8030                        let project = workspace.project().read(cx);
 8031                        if project.is_local() && !project.is_via_collab() {
 8032                            existing = Some(window);
 8033                            open_visible = OpenVisible::None;
 8034                            return;
 8035                        }
 8036                    }
 8037                    for window in local_workspace_windows(cx) {
 8038                        if let Ok(workspace) = window.read(cx) {
 8039                            let project = workspace.project().read(cx);
 8040                            if project.is_via_collab() {
 8041                                continue;
 8042                            }
 8043                            existing = Some(window);
 8044                            open_visible = OpenVisible::None;
 8045                            break;
 8046                        }
 8047                    }
 8048                })?;
 8049            }
 8050        }
 8051
 8052        let result = if let Some(existing) = existing {
 8053            let open_task = existing
 8054                .update(cx, |workspace, window, cx| {
 8055                    window.activate_window();
 8056                    workspace.open_paths(
 8057                        abs_paths,
 8058                        OpenOptions {
 8059                            visible: Some(open_visible),
 8060                            ..Default::default()
 8061                        },
 8062                        None,
 8063                        window,
 8064                        cx,
 8065                    )
 8066                })?
 8067                .await;
 8068
 8069            _ = existing.update(cx, |workspace, _, cx| {
 8070                for item in open_task.iter().flatten() {
 8071                    if let Err(e) = item {
 8072                        workspace.show_error(&e, cx);
 8073                    }
 8074                }
 8075            });
 8076
 8077            Ok((existing, open_task))
 8078        } else {
 8079            cx.update(move |cx| {
 8080                Workspace::new_local(
 8081                    abs_paths,
 8082                    app_state.clone(),
 8083                    open_options.replace_window,
 8084                    open_options.env,
 8085                    None,
 8086                    cx,
 8087                )
 8088            })?
 8089            .await
 8090        };
 8091
 8092        #[cfg(target_os = "windows")]
 8093        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8094            && let Ok((workspace, _)) = &result
 8095        {
 8096            workspace
 8097                .update(cx, move |workspace, _window, cx| {
 8098                    struct OpenInWsl;
 8099                    workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8100                        let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8101                        let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8102                        cx.new(move |cx| {
 8103                            MessageNotification::new(msg, cx)
 8104                                .primary_message("Open in WSL")
 8105                                .primary_icon(IconName::FolderOpen)
 8106                                .primary_on_click(move |window, cx| {
 8107                                    window.dispatch_action(Box::new(remote::OpenWslPath {
 8108                                            distro: remote::WslConnectionOptions {
 8109                                                    distro_name: distro.clone(),
 8110                                                user: None,
 8111                                            },
 8112                                            paths: vec![path.clone().into()],
 8113                                        }), cx)
 8114                                })
 8115                        })
 8116                    });
 8117                })
 8118                .unwrap();
 8119        };
 8120        result
 8121    })
 8122}
 8123
 8124pub fn open_new(
 8125    open_options: OpenOptions,
 8126    app_state: Arc<AppState>,
 8127    cx: &mut App,
 8128    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8129) -> Task<anyhow::Result<()>> {
 8130    let task = Workspace::new_local(
 8131        Vec::new(),
 8132        app_state,
 8133        None,
 8134        open_options.env,
 8135        Some(Box::new(init)),
 8136        cx,
 8137    );
 8138    cx.spawn(async move |_cx| {
 8139        let (_workspace, _opened_paths) = task.await?;
 8140        // Init callback is called synchronously during workspace creation
 8141        Ok(())
 8142    })
 8143}
 8144
 8145pub fn create_and_open_local_file(
 8146    path: &'static Path,
 8147    window: &mut Window,
 8148    cx: &mut Context<Workspace>,
 8149    default_content: impl 'static + Send + FnOnce() -> Rope,
 8150) -> Task<Result<Box<dyn ItemHandle>>> {
 8151    cx.spawn_in(window, async move |workspace, cx| {
 8152        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8153        if !fs.is_file(path).await {
 8154            fs.create_file(path, Default::default()).await?;
 8155            fs.save(path, &default_content(), Default::default())
 8156                .await?;
 8157        }
 8158
 8159        let mut items = workspace
 8160            .update_in(cx, |workspace, window, cx| {
 8161                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 8162                    workspace.open_paths(
 8163                        vec![path.to_path_buf()],
 8164                        OpenOptions {
 8165                            visible: Some(OpenVisible::None),
 8166                            ..Default::default()
 8167                        },
 8168                        None,
 8169                        window,
 8170                        cx,
 8171                    )
 8172                })
 8173            })?
 8174            .await?
 8175            .await;
 8176
 8177        let item = items.pop().flatten();
 8178        item.with_context(|| format!("path {path:?} is not a file"))?
 8179    })
 8180}
 8181
 8182pub fn open_remote_project_with_new_connection(
 8183    window: WindowHandle<Workspace>,
 8184    remote_connection: Arc<dyn RemoteConnection>,
 8185    cancel_rx: oneshot::Receiver<()>,
 8186    delegate: Arc<dyn RemoteClientDelegate>,
 8187    app_state: Arc<AppState>,
 8188    paths: Vec<PathBuf>,
 8189    cx: &mut App,
 8190) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8191    cx.spawn(async move |cx| {
 8192        let (workspace_id, serialized_workspace) =
 8193            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8194                .await?;
 8195
 8196        let session = match cx
 8197            .update(|cx| {
 8198                remote::RemoteClient::new(
 8199                    ConnectionIdentifier::Workspace(workspace_id.0),
 8200                    remote_connection,
 8201                    cancel_rx,
 8202                    delegate,
 8203                    cx,
 8204                )
 8205            })?
 8206            .await?
 8207        {
 8208            Some(result) => result,
 8209            None => return Ok(Vec::new()),
 8210        };
 8211
 8212        let project = cx.update(|cx| {
 8213            project::Project::remote(
 8214                session,
 8215                app_state.client.clone(),
 8216                app_state.node_runtime.clone(),
 8217                app_state.user_store.clone(),
 8218                app_state.languages.clone(),
 8219                app_state.fs.clone(),
 8220                true,
 8221                cx,
 8222            )
 8223        })?;
 8224
 8225        open_remote_project_inner(
 8226            project,
 8227            paths,
 8228            workspace_id,
 8229            serialized_workspace,
 8230            app_state,
 8231            window,
 8232            cx,
 8233        )
 8234        .await
 8235    })
 8236}
 8237
 8238pub fn open_remote_project_with_existing_connection(
 8239    connection_options: RemoteConnectionOptions,
 8240    project: Entity<Project>,
 8241    paths: Vec<PathBuf>,
 8242    app_state: Arc<AppState>,
 8243    window: WindowHandle<Workspace>,
 8244    cx: &mut AsyncApp,
 8245) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8246    cx.spawn(async move |cx| {
 8247        let (workspace_id, serialized_workspace) =
 8248            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 8249
 8250        open_remote_project_inner(
 8251            project,
 8252            paths,
 8253            workspace_id,
 8254            serialized_workspace,
 8255            app_state,
 8256            window,
 8257            cx,
 8258        )
 8259        .await
 8260    })
 8261}
 8262
 8263async fn open_remote_project_inner(
 8264    project: Entity<Project>,
 8265    paths: Vec<PathBuf>,
 8266    workspace_id: WorkspaceId,
 8267    serialized_workspace: Option<SerializedWorkspace>,
 8268    app_state: Arc<AppState>,
 8269    window: WindowHandle<Workspace>,
 8270    cx: &mut AsyncApp,
 8271) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 8272    let toolchains = DB.toolchains(workspace_id).await?;
 8273    for (toolchain, worktree_path, path) in toolchains {
 8274        project
 8275            .update(cx, |this, cx| {
 8276                let Some(worktree_id) =
 8277                    this.find_worktree(&worktree_path, cx)
 8278                        .and_then(|(worktree, rel_path)| {
 8279                            if rel_path.is_empty() {
 8280                                Some(worktree.read(cx).id())
 8281                            } else {
 8282                                None
 8283                            }
 8284                        })
 8285                else {
 8286                    return Task::ready(None);
 8287                };
 8288
 8289                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 8290            })?
 8291            .await;
 8292    }
 8293    let mut project_paths_to_open = vec![];
 8294    let mut project_path_errors = vec![];
 8295
 8296    for path in paths {
 8297        let result = cx
 8298            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 8299            .await;
 8300        match result {
 8301            Ok((_, project_path)) => {
 8302                project_paths_to_open.push((path.clone(), Some(project_path)));
 8303            }
 8304            Err(error) => {
 8305                project_path_errors.push(error);
 8306            }
 8307        };
 8308    }
 8309
 8310    if project_paths_to_open.is_empty() {
 8311        return Err(project_path_errors.pop().context("no paths given")?);
 8312    }
 8313
 8314    if let Some(detach_session_task) = window
 8315        .update(cx, |_workspace, window, cx| {
 8316            cx.spawn_in(window, async move |this, cx| {
 8317                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 8318            })
 8319        })
 8320        .ok()
 8321    {
 8322        detach_session_task.await.ok();
 8323    }
 8324
 8325    cx.update_window(window.into(), |_, window, cx| {
 8326        window.replace_root(cx, |window, cx| {
 8327            telemetry::event!("SSH Project Opened");
 8328
 8329            let mut workspace =
 8330                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 8331            workspace.update_history(cx);
 8332
 8333            if let Some(ref serialized) = serialized_workspace {
 8334                workspace.centered_layout = serialized.centered_layout;
 8335            }
 8336
 8337            workspace
 8338        });
 8339    })?;
 8340
 8341    let items = window
 8342        .update(cx, |_, window, cx| {
 8343            window.activate_window();
 8344            open_items(serialized_workspace, project_paths_to_open, window, cx)
 8345        })?
 8346        .await?;
 8347
 8348    window.update(cx, |workspace, _, cx| {
 8349        for error in project_path_errors {
 8350            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 8351                if let Some(path) = error.error_tag("path") {
 8352                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 8353                }
 8354            } else {
 8355                workspace.show_error(&error, cx)
 8356            }
 8357        }
 8358    })?;
 8359
 8360    Ok(items.into_iter().map(|item| item?.ok()).collect())
 8361}
 8362
 8363fn deserialize_remote_project(
 8364    connection_options: RemoteConnectionOptions,
 8365    paths: Vec<PathBuf>,
 8366    cx: &AsyncApp,
 8367) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 8368    cx.background_spawn(async move {
 8369        let remote_connection_id = persistence::DB
 8370            .get_or_create_remote_connection(connection_options)
 8371            .await?;
 8372
 8373        let serialized_workspace =
 8374            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8375
 8376        let workspace_id = if let Some(workspace_id) =
 8377            serialized_workspace.as_ref().map(|workspace| workspace.id)
 8378        {
 8379            workspace_id
 8380        } else {
 8381            persistence::DB.next_id().await?
 8382        };
 8383
 8384        Ok((workspace_id, serialized_workspace))
 8385    })
 8386}
 8387
 8388pub fn join_in_room_project(
 8389    project_id: u64,
 8390    follow_user_id: u64,
 8391    app_state: Arc<AppState>,
 8392    cx: &mut App,
 8393) -> Task<Result<()>> {
 8394    let windows = cx.windows();
 8395    cx.spawn(async move |cx| {
 8396        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 8397            window_handle
 8398                .downcast::<Workspace>()
 8399                .and_then(|window_handle| {
 8400                    window_handle
 8401                        .update(cx, |workspace, _window, cx| {
 8402                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 8403                                Some(window_handle)
 8404                            } else {
 8405                                None
 8406                            }
 8407                        })
 8408                        .unwrap_or(None)
 8409                })
 8410        });
 8411
 8412        let workspace = if let Some(existing_workspace) = existing_workspace {
 8413            existing_workspace
 8414        } else {
 8415            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 8416            let room = active_call
 8417                .read_with(cx, |call, _| call.room().cloned())?
 8418                .context("not in a call")?;
 8419            let project = room
 8420                .update(cx, |room, cx| {
 8421                    room.join_project(
 8422                        project_id,
 8423                        app_state.languages.clone(),
 8424                        app_state.fs.clone(),
 8425                        cx,
 8426                    )
 8427                })?
 8428                .await?;
 8429
 8430            let window_bounds_override = window_bounds_env_override();
 8431            cx.update(|cx| {
 8432                let mut options = (app_state.build_window_options)(None, cx);
 8433                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 8434                cx.open_window(options, |window, cx| {
 8435                    cx.new(|cx| {
 8436                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 8437                    })
 8438                })
 8439            })??
 8440        };
 8441
 8442        workspace.update(cx, |workspace, window, cx| {
 8443            cx.activate(true);
 8444            window.activate_window();
 8445
 8446            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 8447                let follow_peer_id = room
 8448                    .read(cx)
 8449                    .remote_participants()
 8450                    .iter()
 8451                    .find(|(_, participant)| participant.user.id == follow_user_id)
 8452                    .map(|(_, p)| p.peer_id)
 8453                    .or_else(|| {
 8454                        // If we couldn't follow the given user, follow the host instead.
 8455                        let collaborator = workspace
 8456                            .project()
 8457                            .read(cx)
 8458                            .collaborators()
 8459                            .values()
 8460                            .find(|collaborator| collaborator.is_host)?;
 8461                        Some(collaborator.peer_id)
 8462                    });
 8463
 8464                if let Some(follow_peer_id) = follow_peer_id {
 8465                    workspace.follow(follow_peer_id, window, cx);
 8466                }
 8467            }
 8468        })?;
 8469
 8470        anyhow::Ok(())
 8471    })
 8472}
 8473
 8474pub fn reload(cx: &mut App) {
 8475    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 8476    let mut workspace_windows = cx
 8477        .windows()
 8478        .into_iter()
 8479        .filter_map(|window| window.downcast::<Workspace>())
 8480        .collect::<Vec<_>>();
 8481
 8482    // If multiple windows have unsaved changes, and need a save prompt,
 8483    // prompt in the active window before switching to a different window.
 8484    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 8485
 8486    let mut prompt = None;
 8487    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 8488        prompt = window
 8489            .update(cx, |_, window, cx| {
 8490                window.prompt(
 8491                    PromptLevel::Info,
 8492                    "Are you sure you want to restart?",
 8493                    None,
 8494                    &["Restart", "Cancel"],
 8495                    cx,
 8496                )
 8497            })
 8498            .ok();
 8499    }
 8500
 8501    cx.spawn(async move |cx| {
 8502        if let Some(prompt) = prompt {
 8503            let answer = prompt.await?;
 8504            if answer != 0 {
 8505                return Ok(());
 8506            }
 8507        }
 8508
 8509        // If the user cancels any save prompt, then keep the app open.
 8510        for window in workspace_windows {
 8511            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 8512                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 8513            }) && !should_close.await?
 8514            {
 8515                return Ok(());
 8516            }
 8517        }
 8518        cx.update(|cx| cx.restart())
 8519    })
 8520    .detach_and_log_err(cx);
 8521}
 8522
 8523fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 8524    let mut parts = value.split(',');
 8525    let x: usize = parts.next()?.parse().ok()?;
 8526    let y: usize = parts.next()?.parse().ok()?;
 8527    Some(point(px(x as f32), px(y as f32)))
 8528}
 8529
 8530fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 8531    let mut parts = value.split(',');
 8532    let width: usize = parts.next()?.parse().ok()?;
 8533    let height: usize = parts.next()?.parse().ok()?;
 8534    Some(size(px(width as f32), px(height as f32)))
 8535}
 8536
 8537/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 8538pub fn client_side_decorations(
 8539    element: impl IntoElement,
 8540    window: &mut Window,
 8541    cx: &mut App,
 8542) -> Stateful<Div> {
 8543    const BORDER_SIZE: Pixels = px(1.0);
 8544    let decorations = window.window_decorations();
 8545
 8546    match decorations {
 8547        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 8548        Decorations::Server => window.set_client_inset(px(0.0)),
 8549    }
 8550
 8551    struct GlobalResizeEdge(ResizeEdge);
 8552    impl Global for GlobalResizeEdge {}
 8553
 8554    div()
 8555        .id("window-backdrop")
 8556        .bg(transparent_black())
 8557        .map(|div| match decorations {
 8558            Decorations::Server => div,
 8559            Decorations::Client { tiling, .. } => div
 8560                .when(!(tiling.top || tiling.right), |div| {
 8561                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8562                })
 8563                .when(!(tiling.top || tiling.left), |div| {
 8564                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8565                })
 8566                .when(!(tiling.bottom || tiling.right), |div| {
 8567                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8568                })
 8569                .when(!(tiling.bottom || tiling.left), |div| {
 8570                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8571                })
 8572                .when(!tiling.top, |div| {
 8573                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8574                })
 8575                .when(!tiling.bottom, |div| {
 8576                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8577                })
 8578                .when(!tiling.left, |div| {
 8579                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8580                })
 8581                .when(!tiling.right, |div| {
 8582                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8583                })
 8584                .on_mouse_move(move |e, window, cx| {
 8585                    let size = window.window_bounds().get_bounds().size;
 8586                    let pos = e.position;
 8587
 8588                    let new_edge =
 8589                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8590
 8591                    let edge = cx.try_global::<GlobalResizeEdge>();
 8592                    if new_edge != edge.map(|edge| edge.0) {
 8593                        window
 8594                            .window_handle()
 8595                            .update(cx, |workspace, _, cx| {
 8596                                cx.notify(workspace.entity_id());
 8597                            })
 8598                            .ok();
 8599                    }
 8600                })
 8601                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8602                    let size = window.window_bounds().get_bounds().size;
 8603                    let pos = e.position;
 8604
 8605                    let edge = match resize_edge(
 8606                        pos,
 8607                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8608                        size,
 8609                        tiling,
 8610                    ) {
 8611                        Some(value) => value,
 8612                        None => return,
 8613                    };
 8614
 8615                    window.start_window_resize(edge);
 8616                }),
 8617        })
 8618        .size_full()
 8619        .child(
 8620            div()
 8621                .cursor(CursorStyle::Arrow)
 8622                .map(|div| match decorations {
 8623                    Decorations::Server => div,
 8624                    Decorations::Client { tiling } => div
 8625                        .border_color(cx.theme().colors().border)
 8626                        .when(!(tiling.top || tiling.right), |div| {
 8627                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8628                        })
 8629                        .when(!(tiling.top || tiling.left), |div| {
 8630                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8631                        })
 8632                        .when(!(tiling.bottom || tiling.right), |div| {
 8633                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8634                        })
 8635                        .when(!(tiling.bottom || tiling.left), |div| {
 8636                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8637                        })
 8638                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8639                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8640                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8641                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8642                        .when(!tiling.is_tiled(), |div| {
 8643                            div.shadow(vec![gpui::BoxShadow {
 8644                                color: Hsla {
 8645                                    h: 0.,
 8646                                    s: 0.,
 8647                                    l: 0.,
 8648                                    a: 0.4,
 8649                                },
 8650                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8651                                spread_radius: px(0.),
 8652                                offset: point(px(0.0), px(0.0)),
 8653                            }])
 8654                        }),
 8655                })
 8656                .on_mouse_move(|_e, _, cx| {
 8657                    cx.stop_propagation();
 8658                })
 8659                .size_full()
 8660                .child(element),
 8661        )
 8662        .map(|div| match decorations {
 8663            Decorations::Server => div,
 8664            Decorations::Client { tiling, .. } => div.child(
 8665                canvas(
 8666                    |_bounds, window, _| {
 8667                        window.insert_hitbox(
 8668                            Bounds::new(
 8669                                point(px(0.0), px(0.0)),
 8670                                window.window_bounds().get_bounds().size,
 8671                            ),
 8672                            HitboxBehavior::Normal,
 8673                        )
 8674                    },
 8675                    move |_bounds, hitbox, window, cx| {
 8676                        let mouse = window.mouse_position();
 8677                        let size = window.window_bounds().get_bounds().size;
 8678                        let Some(edge) =
 8679                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8680                        else {
 8681                            return;
 8682                        };
 8683                        cx.set_global(GlobalResizeEdge(edge));
 8684                        window.set_cursor_style(
 8685                            match edge {
 8686                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8687                                ResizeEdge::Left | ResizeEdge::Right => {
 8688                                    CursorStyle::ResizeLeftRight
 8689                                }
 8690                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8691                                    CursorStyle::ResizeUpLeftDownRight
 8692                                }
 8693                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8694                                    CursorStyle::ResizeUpRightDownLeft
 8695                                }
 8696                            },
 8697                            &hitbox,
 8698                        );
 8699                    },
 8700                )
 8701                .size_full()
 8702                .absolute(),
 8703            ),
 8704        })
 8705}
 8706
 8707fn resize_edge(
 8708    pos: Point<Pixels>,
 8709    shadow_size: Pixels,
 8710    window_size: Size<Pixels>,
 8711    tiling: Tiling,
 8712) -> Option<ResizeEdge> {
 8713    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8714    if bounds.contains(&pos) {
 8715        return None;
 8716    }
 8717
 8718    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8719    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8720    if !tiling.top && top_left_bounds.contains(&pos) {
 8721        return Some(ResizeEdge::TopLeft);
 8722    }
 8723
 8724    let top_right_bounds = Bounds::new(
 8725        Point::new(window_size.width - corner_size.width, px(0.)),
 8726        corner_size,
 8727    );
 8728    if !tiling.top && top_right_bounds.contains(&pos) {
 8729        return Some(ResizeEdge::TopRight);
 8730    }
 8731
 8732    let bottom_left_bounds = Bounds::new(
 8733        Point::new(px(0.), window_size.height - corner_size.height),
 8734        corner_size,
 8735    );
 8736    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8737        return Some(ResizeEdge::BottomLeft);
 8738    }
 8739
 8740    let bottom_right_bounds = Bounds::new(
 8741        Point::new(
 8742            window_size.width - corner_size.width,
 8743            window_size.height - corner_size.height,
 8744        ),
 8745        corner_size,
 8746    );
 8747    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8748        return Some(ResizeEdge::BottomRight);
 8749    }
 8750
 8751    if !tiling.top && pos.y < shadow_size {
 8752        Some(ResizeEdge::Top)
 8753    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8754        Some(ResizeEdge::Bottom)
 8755    } else if !tiling.left && pos.x < shadow_size {
 8756        Some(ResizeEdge::Left)
 8757    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8758        Some(ResizeEdge::Right)
 8759    } else {
 8760        None
 8761    }
 8762}
 8763
 8764fn join_pane_into_active(
 8765    active_pane: &Entity<Pane>,
 8766    pane: &Entity<Pane>,
 8767    window: &mut Window,
 8768    cx: &mut App,
 8769) {
 8770    if pane == active_pane {
 8771    } else if pane.read(cx).items_len() == 0 {
 8772        pane.update(cx, |_, cx| {
 8773            cx.emit(pane::Event::Remove {
 8774                focus_on_pane: None,
 8775            });
 8776        })
 8777    } else {
 8778        move_all_items(pane, active_pane, window, cx);
 8779    }
 8780}
 8781
 8782fn move_all_items(
 8783    from_pane: &Entity<Pane>,
 8784    to_pane: &Entity<Pane>,
 8785    window: &mut Window,
 8786    cx: &mut App,
 8787) {
 8788    let destination_is_different = from_pane != to_pane;
 8789    let mut moved_items = 0;
 8790    for (item_ix, item_handle) in from_pane
 8791        .read(cx)
 8792        .items()
 8793        .enumerate()
 8794        .map(|(ix, item)| (ix, item.clone()))
 8795        .collect::<Vec<_>>()
 8796    {
 8797        let ix = item_ix - moved_items;
 8798        if destination_is_different {
 8799            // Close item from previous pane
 8800            from_pane.update(cx, |source, cx| {
 8801                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8802            });
 8803            moved_items += 1;
 8804        }
 8805
 8806        // This automatically removes duplicate items in the pane
 8807        to_pane.update(cx, |destination, cx| {
 8808            destination.add_item(item_handle, true, true, None, window, cx);
 8809            window.focus(&destination.focus_handle(cx), cx)
 8810        });
 8811    }
 8812}
 8813
 8814pub fn move_item(
 8815    source: &Entity<Pane>,
 8816    destination: &Entity<Pane>,
 8817    item_id_to_move: EntityId,
 8818    destination_index: usize,
 8819    activate: bool,
 8820    window: &mut Window,
 8821    cx: &mut App,
 8822) {
 8823    let Some((item_ix, item_handle)) = source
 8824        .read(cx)
 8825        .items()
 8826        .enumerate()
 8827        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8828        .map(|(ix, item)| (ix, item.clone()))
 8829    else {
 8830        // Tab was closed during drag
 8831        return;
 8832    };
 8833
 8834    if source != destination {
 8835        // Close item from previous pane
 8836        source.update(cx, |source, cx| {
 8837            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8838        });
 8839    }
 8840
 8841    // This automatically removes duplicate items in the pane
 8842    destination.update(cx, |destination, cx| {
 8843        destination.add_item_inner(
 8844            item_handle,
 8845            activate,
 8846            activate,
 8847            activate,
 8848            Some(destination_index),
 8849            window,
 8850            cx,
 8851        );
 8852        if activate {
 8853            window.focus(&destination.focus_handle(cx), cx)
 8854        }
 8855    });
 8856}
 8857
 8858pub fn move_active_item(
 8859    source: &Entity<Pane>,
 8860    destination: &Entity<Pane>,
 8861    focus_destination: bool,
 8862    close_if_empty: bool,
 8863    window: &mut Window,
 8864    cx: &mut App,
 8865) {
 8866    if source == destination {
 8867        return;
 8868    }
 8869    let Some(active_item) = source.read(cx).active_item() else {
 8870        return;
 8871    };
 8872    source.update(cx, |source_pane, cx| {
 8873        let item_id = active_item.item_id();
 8874        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8875        destination.update(cx, |target_pane, cx| {
 8876            target_pane.add_item(
 8877                active_item,
 8878                focus_destination,
 8879                focus_destination,
 8880                Some(target_pane.items_len()),
 8881                window,
 8882                cx,
 8883            );
 8884        });
 8885    });
 8886}
 8887
 8888pub fn clone_active_item(
 8889    workspace_id: Option<WorkspaceId>,
 8890    source: &Entity<Pane>,
 8891    destination: &Entity<Pane>,
 8892    focus_destination: bool,
 8893    window: &mut Window,
 8894    cx: &mut App,
 8895) {
 8896    if source == destination {
 8897        return;
 8898    }
 8899    let Some(active_item) = source.read(cx).active_item() else {
 8900        return;
 8901    };
 8902    if !active_item.can_split(cx) {
 8903        return;
 8904    }
 8905    let destination = destination.downgrade();
 8906    let task = active_item.clone_on_split(workspace_id, window, cx);
 8907    window
 8908        .spawn(cx, async move |cx| {
 8909            let Some(clone) = task.await else {
 8910                return;
 8911            };
 8912            destination
 8913                .update_in(cx, |target_pane, window, cx| {
 8914                    target_pane.add_item(
 8915                        clone,
 8916                        focus_destination,
 8917                        focus_destination,
 8918                        Some(target_pane.items_len()),
 8919                        window,
 8920                        cx,
 8921                    );
 8922                })
 8923                .log_err();
 8924        })
 8925        .detach();
 8926}
 8927
 8928#[derive(Debug)]
 8929pub struct WorkspacePosition {
 8930    pub window_bounds: Option<WindowBounds>,
 8931    pub display: Option<Uuid>,
 8932    pub centered_layout: bool,
 8933}
 8934
 8935pub fn remote_workspace_position_from_db(
 8936    connection_options: RemoteConnectionOptions,
 8937    paths_to_open: &[PathBuf],
 8938    cx: &App,
 8939) -> Task<Result<WorkspacePosition>> {
 8940    let paths = paths_to_open.to_vec();
 8941
 8942    cx.background_spawn(async move {
 8943        let remote_connection_id = persistence::DB
 8944            .get_or_create_remote_connection(connection_options)
 8945            .await
 8946            .context("fetching serialized ssh project")?;
 8947        let serialized_workspace =
 8948            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8949
 8950        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8951            (Some(WindowBounds::Windowed(bounds)), None)
 8952        } else {
 8953            let restorable_bounds = serialized_workspace
 8954                .as_ref()
 8955                .and_then(|workspace| {
 8956                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 8957                })
 8958                .or_else(|| persistence::read_default_window_bounds());
 8959
 8960            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 8961                (Some(serialized_bounds), Some(serialized_display))
 8962            } else {
 8963                (None, None)
 8964            }
 8965        };
 8966
 8967        let centered_layout = serialized_workspace
 8968            .as_ref()
 8969            .map(|w| w.centered_layout)
 8970            .unwrap_or(false);
 8971
 8972        Ok(WorkspacePosition {
 8973            window_bounds,
 8974            display,
 8975            centered_layout,
 8976        })
 8977    })
 8978}
 8979
 8980pub fn with_active_or_new_workspace(
 8981    cx: &mut App,
 8982    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8983) {
 8984    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8985        Some(workspace) => {
 8986            cx.defer(move |cx| {
 8987                workspace
 8988                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8989                    .log_err();
 8990            });
 8991        }
 8992        None => {
 8993            let app_state = AppState::global(cx);
 8994            if let Some(app_state) = app_state.upgrade() {
 8995                open_new(
 8996                    OpenOptions::default(),
 8997                    app_state,
 8998                    cx,
 8999                    move |workspace, window, cx| f(workspace, window, cx),
 9000                )
 9001                .detach_and_log_err(cx);
 9002            }
 9003        }
 9004    }
 9005}
 9006
 9007#[cfg(test)]
 9008mod tests {
 9009    use std::{cell::RefCell, rc::Rc};
 9010
 9011    use super::*;
 9012    use crate::{
 9013        dock::{PanelEvent, test::TestPanel},
 9014        item::{
 9015            ItemBufferKind, ItemEvent,
 9016            test::{TestItem, TestProjectItem},
 9017        },
 9018    };
 9019    use fs::FakeFs;
 9020    use gpui::{
 9021        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9022        UpdateGlobal, VisualTestContext, px,
 9023    };
 9024    use project::{Project, ProjectEntryId};
 9025    use serde_json::json;
 9026    use settings::SettingsStore;
 9027    use util::rel_path::rel_path;
 9028
 9029    #[gpui::test]
 9030    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9031        init_test(cx);
 9032
 9033        let fs = FakeFs::new(cx.executor());
 9034        let project = Project::test(fs, [], cx).await;
 9035        let (workspace, cx) =
 9036            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9037
 9038        // Adding an item with no ambiguity renders the tab without detail.
 9039        let item1 = cx.new(|cx| {
 9040            let mut item = TestItem::new(cx);
 9041            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9042            item
 9043        });
 9044        workspace.update_in(cx, |workspace, window, cx| {
 9045            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9046        });
 9047        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9048
 9049        // Adding an item that creates ambiguity increases the level of detail on
 9050        // both tabs.
 9051        let item2 = cx.new_window_entity(|_window, cx| {
 9052            let mut item = TestItem::new(cx);
 9053            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9054            item
 9055        });
 9056        workspace.update_in(cx, |workspace, window, cx| {
 9057            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9058        });
 9059        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9060        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9061
 9062        // Adding an item that creates ambiguity increases the level of detail only
 9063        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9064        // we stop at the highest detail available.
 9065        let item3 = cx.new(|cx| {
 9066            let mut item = TestItem::new(cx);
 9067            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9068            item
 9069        });
 9070        workspace.update_in(cx, |workspace, window, cx| {
 9071            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9072        });
 9073        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9074        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9075        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9076    }
 9077
 9078    #[gpui::test]
 9079    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9080        init_test(cx);
 9081
 9082        let fs = FakeFs::new(cx.executor());
 9083        fs.insert_tree(
 9084            "/root1",
 9085            json!({
 9086                "one.txt": "",
 9087                "two.txt": "",
 9088            }),
 9089        )
 9090        .await;
 9091        fs.insert_tree(
 9092            "/root2",
 9093            json!({
 9094                "three.txt": "",
 9095            }),
 9096        )
 9097        .await;
 9098
 9099        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9100        let (workspace, cx) =
 9101            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9102        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9103        let worktree_id = project.update(cx, |project, cx| {
 9104            project.worktrees(cx).next().unwrap().read(cx).id()
 9105        });
 9106
 9107        let item1 = cx.new(|cx| {
 9108            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9109        });
 9110        let item2 = cx.new(|cx| {
 9111            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9112        });
 9113
 9114        // Add an item to an empty pane
 9115        workspace.update_in(cx, |workspace, window, cx| {
 9116            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9117        });
 9118        project.update(cx, |project, cx| {
 9119            assert_eq!(
 9120                project.active_entry(),
 9121                project
 9122                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9123                    .map(|e| e.id)
 9124            );
 9125        });
 9126        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9127
 9128        // Add a second item to a non-empty pane
 9129        workspace.update_in(cx, |workspace, window, cx| {
 9130            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9131        });
 9132        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9133        project.update(cx, |project, cx| {
 9134            assert_eq!(
 9135                project.active_entry(),
 9136                project
 9137                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9138                    .map(|e| e.id)
 9139            );
 9140        });
 9141
 9142        // Close the active item
 9143        pane.update_in(cx, |pane, window, cx| {
 9144            pane.close_active_item(&Default::default(), window, cx)
 9145        })
 9146        .await
 9147        .unwrap();
 9148        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9149        project.update(cx, |project, cx| {
 9150            assert_eq!(
 9151                project.active_entry(),
 9152                project
 9153                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9154                    .map(|e| e.id)
 9155            );
 9156        });
 9157
 9158        // Add a project folder
 9159        project
 9160            .update(cx, |project, cx| {
 9161                project.find_or_create_worktree("root2", true, cx)
 9162            })
 9163            .await
 9164            .unwrap();
 9165        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 9166
 9167        // Remove a project folder
 9168        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 9169        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 9170    }
 9171
 9172    #[gpui::test]
 9173    async fn test_close_window(cx: &mut TestAppContext) {
 9174        init_test(cx);
 9175
 9176        let fs = FakeFs::new(cx.executor());
 9177        fs.insert_tree("/root", json!({ "one": "" })).await;
 9178
 9179        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9180        let (workspace, cx) =
 9181            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9182
 9183        // When there are no dirty items, there's nothing to do.
 9184        let item1 = cx.new(TestItem::new);
 9185        workspace.update_in(cx, |w, window, cx| {
 9186            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 9187        });
 9188        let task = workspace.update_in(cx, |w, window, cx| {
 9189            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9190        });
 9191        assert!(task.await.unwrap());
 9192
 9193        // When there are dirty untitled items, prompt to save each one. If the user
 9194        // cancels any prompt, then abort.
 9195        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 9196        let item3 = cx.new(|cx| {
 9197            TestItem::new(cx)
 9198                .with_dirty(true)
 9199                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9200        });
 9201        workspace.update_in(cx, |w, window, cx| {
 9202            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9203            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9204        });
 9205        let task = workspace.update_in(cx, |w, window, cx| {
 9206            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9207        });
 9208        cx.executor().run_until_parked();
 9209        cx.simulate_prompt_answer("Cancel"); // cancel save all
 9210        cx.executor().run_until_parked();
 9211        assert!(!cx.has_pending_prompt());
 9212        assert!(!task.await.unwrap());
 9213    }
 9214
 9215    #[gpui::test]
 9216    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 9217        init_test(cx);
 9218
 9219        // Register TestItem as a serializable item
 9220        cx.update(|cx| {
 9221            register_serializable_item::<TestItem>(cx);
 9222        });
 9223
 9224        let fs = FakeFs::new(cx.executor());
 9225        fs.insert_tree("/root", json!({ "one": "" })).await;
 9226
 9227        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9228        let (workspace, cx) =
 9229            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9230
 9231        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 9232        let item1 = cx.new(|cx| {
 9233            TestItem::new(cx)
 9234                .with_dirty(true)
 9235                .with_serialize(|| Some(Task::ready(Ok(()))))
 9236        });
 9237        let item2 = cx.new(|cx| {
 9238            TestItem::new(cx)
 9239                .with_dirty(true)
 9240                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9241                .with_serialize(|| Some(Task::ready(Ok(()))))
 9242        });
 9243        workspace.update_in(cx, |w, window, cx| {
 9244            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9245            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9246        });
 9247        let task = workspace.update_in(cx, |w, window, cx| {
 9248            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9249        });
 9250        assert!(task.await.unwrap());
 9251    }
 9252
 9253    #[gpui::test]
 9254    async fn test_close_pane_items(cx: &mut TestAppContext) {
 9255        init_test(cx);
 9256
 9257        let fs = FakeFs::new(cx.executor());
 9258
 9259        let project = Project::test(fs, None, cx).await;
 9260        let (workspace, cx) =
 9261            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9262
 9263        let item1 = cx.new(|cx| {
 9264            TestItem::new(cx)
 9265                .with_dirty(true)
 9266                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9267        });
 9268        let item2 = cx.new(|cx| {
 9269            TestItem::new(cx)
 9270                .with_dirty(true)
 9271                .with_conflict(true)
 9272                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9273        });
 9274        let item3 = cx.new(|cx| {
 9275            TestItem::new(cx)
 9276                .with_dirty(true)
 9277                .with_conflict(true)
 9278                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 9279        });
 9280        let item4 = cx.new(|cx| {
 9281            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 9282                let project_item = TestProjectItem::new_untitled(cx);
 9283                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9284                project_item
 9285            }])
 9286        });
 9287        let pane = workspace.update_in(cx, |workspace, window, cx| {
 9288            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9289            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9290            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9291            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 9292            workspace.active_pane().clone()
 9293        });
 9294
 9295        let close_items = pane.update_in(cx, |pane, window, cx| {
 9296            pane.activate_item(1, true, true, window, cx);
 9297            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9298            let item1_id = item1.item_id();
 9299            let item3_id = item3.item_id();
 9300            let item4_id = item4.item_id();
 9301            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 9302                [item1_id, item3_id, item4_id].contains(&id)
 9303            })
 9304        });
 9305        cx.executor().run_until_parked();
 9306
 9307        assert!(cx.has_pending_prompt());
 9308        cx.simulate_prompt_answer("Save all");
 9309
 9310        cx.executor().run_until_parked();
 9311
 9312        // Item 1 is saved. There's a prompt to save item 3.
 9313        pane.update(cx, |pane, cx| {
 9314            assert_eq!(item1.read(cx).save_count, 1);
 9315            assert_eq!(item1.read(cx).save_as_count, 0);
 9316            assert_eq!(item1.read(cx).reload_count, 0);
 9317            assert_eq!(pane.items_len(), 3);
 9318            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 9319        });
 9320        assert!(cx.has_pending_prompt());
 9321
 9322        // Cancel saving item 3.
 9323        cx.simulate_prompt_answer("Discard");
 9324        cx.executor().run_until_parked();
 9325
 9326        // Item 3 is reloaded. There's a prompt to save item 4.
 9327        pane.update(cx, |pane, cx| {
 9328            assert_eq!(item3.read(cx).save_count, 0);
 9329            assert_eq!(item3.read(cx).save_as_count, 0);
 9330            assert_eq!(item3.read(cx).reload_count, 1);
 9331            assert_eq!(pane.items_len(), 2);
 9332            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 9333        });
 9334
 9335        // There's a prompt for a path for item 4.
 9336        cx.simulate_new_path_selection(|_| Some(Default::default()));
 9337        close_items.await.unwrap();
 9338
 9339        // The requested items are closed.
 9340        pane.update(cx, |pane, cx| {
 9341            assert_eq!(item4.read(cx).save_count, 0);
 9342            assert_eq!(item4.read(cx).save_as_count, 1);
 9343            assert_eq!(item4.read(cx).reload_count, 0);
 9344            assert_eq!(pane.items_len(), 1);
 9345            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9346        });
 9347    }
 9348
 9349    #[gpui::test]
 9350    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 9351        init_test(cx);
 9352
 9353        let fs = FakeFs::new(cx.executor());
 9354        let project = Project::test(fs, [], cx).await;
 9355        let (workspace, cx) =
 9356            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9357
 9358        // Create several workspace items with single project entries, and two
 9359        // workspace items with multiple project entries.
 9360        let single_entry_items = (0..=4)
 9361            .map(|project_entry_id| {
 9362                cx.new(|cx| {
 9363                    TestItem::new(cx)
 9364                        .with_dirty(true)
 9365                        .with_project_items(&[dirty_project_item(
 9366                            project_entry_id,
 9367                            &format!("{project_entry_id}.txt"),
 9368                            cx,
 9369                        )])
 9370                })
 9371            })
 9372            .collect::<Vec<_>>();
 9373        let item_2_3 = cx.new(|cx| {
 9374            TestItem::new(cx)
 9375                .with_dirty(true)
 9376                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9377                .with_project_items(&[
 9378                    single_entry_items[2].read(cx).project_items[0].clone(),
 9379                    single_entry_items[3].read(cx).project_items[0].clone(),
 9380                ])
 9381        });
 9382        let item_3_4 = cx.new(|cx| {
 9383            TestItem::new(cx)
 9384                .with_dirty(true)
 9385                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9386                .with_project_items(&[
 9387                    single_entry_items[3].read(cx).project_items[0].clone(),
 9388                    single_entry_items[4].read(cx).project_items[0].clone(),
 9389                ])
 9390        });
 9391
 9392        // Create two panes that contain the following project entries:
 9393        //   left pane:
 9394        //     multi-entry items:   (2, 3)
 9395        //     single-entry items:  0, 2, 3, 4
 9396        //   right pane:
 9397        //     single-entry items:  4, 1
 9398        //     multi-entry items:   (3, 4)
 9399        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 9400            let left_pane = workspace.active_pane().clone();
 9401            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 9402            workspace.add_item_to_active_pane(
 9403                single_entry_items[0].boxed_clone(),
 9404                None,
 9405                true,
 9406                window,
 9407                cx,
 9408            );
 9409            workspace.add_item_to_active_pane(
 9410                single_entry_items[2].boxed_clone(),
 9411                None,
 9412                true,
 9413                window,
 9414                cx,
 9415            );
 9416            workspace.add_item_to_active_pane(
 9417                single_entry_items[3].boxed_clone(),
 9418                None,
 9419                true,
 9420                window,
 9421                cx,
 9422            );
 9423            workspace.add_item_to_active_pane(
 9424                single_entry_items[4].boxed_clone(),
 9425                None,
 9426                true,
 9427                window,
 9428                cx,
 9429            );
 9430
 9431            let right_pane =
 9432                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 9433
 9434            let boxed_clone = single_entry_items[1].boxed_clone();
 9435            let right_pane = window.spawn(cx, async move |cx| {
 9436                right_pane.await.inspect(|right_pane| {
 9437                    right_pane
 9438                        .update_in(cx, |pane, window, cx| {
 9439                            pane.add_item(boxed_clone, true, true, None, window, cx);
 9440                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 9441                        })
 9442                        .unwrap();
 9443                })
 9444            });
 9445
 9446            (left_pane, right_pane)
 9447        });
 9448        let right_pane = right_pane.await.unwrap();
 9449        cx.focus(&right_pane);
 9450
 9451        let close = right_pane.update_in(cx, |pane, window, cx| {
 9452            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9453                .unwrap()
 9454        });
 9455        cx.executor().run_until_parked();
 9456
 9457        let msg = cx.pending_prompt().unwrap().0;
 9458        assert!(msg.contains("1.txt"));
 9459        assert!(!msg.contains("2.txt"));
 9460        assert!(!msg.contains("3.txt"));
 9461        assert!(!msg.contains("4.txt"));
 9462
 9463        // With best-effort close, cancelling item 1 keeps it open but items 4
 9464        // and (3,4) still close since their entries exist in left pane.
 9465        cx.simulate_prompt_answer("Cancel");
 9466        close.await;
 9467
 9468        right_pane.read_with(cx, |pane, _| {
 9469            assert_eq!(pane.items_len(), 1);
 9470        });
 9471
 9472        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
 9473        left_pane
 9474            .update_in(cx, |left_pane, window, cx| {
 9475                left_pane.close_item_by_id(
 9476                    single_entry_items[3].entity_id(),
 9477                    SaveIntent::Skip,
 9478                    window,
 9479                    cx,
 9480                )
 9481            })
 9482            .await
 9483            .unwrap();
 9484
 9485        let close = left_pane.update_in(cx, |pane, window, cx| {
 9486            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9487                .unwrap()
 9488        });
 9489        cx.executor().run_until_parked();
 9490
 9491        let details = cx.pending_prompt().unwrap().1;
 9492        assert!(details.contains("0.txt"));
 9493        assert!(details.contains("3.txt"));
 9494        assert!(details.contains("4.txt"));
 9495        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
 9496        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
 9497        // assert!(!details.contains("2.txt"));
 9498
 9499        cx.simulate_prompt_answer("Save all");
 9500        cx.executor().run_until_parked();
 9501        close.await;
 9502
 9503        left_pane.read_with(cx, |pane, _| {
 9504            assert_eq!(pane.items_len(), 0);
 9505        });
 9506    }
 9507
 9508    #[gpui::test]
 9509    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 9510        init_test(cx);
 9511
 9512        let fs = FakeFs::new(cx.executor());
 9513        let project = Project::test(fs, [], cx).await;
 9514        let (workspace, cx) =
 9515            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9516        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9517
 9518        let item = cx.new(|cx| {
 9519            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9520        });
 9521        let item_id = item.entity_id();
 9522        workspace.update_in(cx, |workspace, window, cx| {
 9523            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9524        });
 9525
 9526        // Autosave on window change.
 9527        item.update(cx, |item, cx| {
 9528            SettingsStore::update_global(cx, |settings, cx| {
 9529                settings.update_user_settings(cx, |settings| {
 9530                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 9531                })
 9532            });
 9533            item.is_dirty = true;
 9534        });
 9535
 9536        // Deactivating the window saves the file.
 9537        cx.deactivate_window();
 9538        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9539
 9540        // Re-activating the window doesn't save the file.
 9541        cx.update(|window, _| window.activate_window());
 9542        cx.executor().run_until_parked();
 9543        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9544
 9545        // Autosave on focus change.
 9546        item.update_in(cx, |item, window, cx| {
 9547            cx.focus_self(window);
 9548            SettingsStore::update_global(cx, |settings, cx| {
 9549                settings.update_user_settings(cx, |settings| {
 9550                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9551                })
 9552            });
 9553            item.is_dirty = true;
 9554        });
 9555        // Blurring the item saves the file.
 9556        item.update_in(cx, |_, window, _| window.blur());
 9557        cx.executor().run_until_parked();
 9558        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 9559
 9560        // Deactivating the window still saves the file.
 9561        item.update_in(cx, |item, window, cx| {
 9562            cx.focus_self(window);
 9563            item.is_dirty = true;
 9564        });
 9565        cx.deactivate_window();
 9566        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 9567
 9568        // Autosave after delay.
 9569        item.update(cx, |item, cx| {
 9570            SettingsStore::update_global(cx, |settings, cx| {
 9571                settings.update_user_settings(cx, |settings| {
 9572                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 9573                        milliseconds: 500.into(),
 9574                    });
 9575                })
 9576            });
 9577            item.is_dirty = true;
 9578            cx.emit(ItemEvent::Edit);
 9579        });
 9580
 9581        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 9582        cx.executor().advance_clock(Duration::from_millis(250));
 9583        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 9584
 9585        // After delay expires, the file is saved.
 9586        cx.executor().advance_clock(Duration::from_millis(250));
 9587        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9588
 9589        // Autosave after delay, should save earlier than delay if tab is closed
 9590        item.update(cx, |item, cx| {
 9591            item.is_dirty = true;
 9592            cx.emit(ItemEvent::Edit);
 9593        });
 9594        cx.executor().advance_clock(Duration::from_millis(250));
 9595        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9596
 9597        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9598        pane.update_in(cx, |pane, window, cx| {
 9599            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9600        })
 9601        .await
 9602        .unwrap();
 9603        assert!(!cx.has_pending_prompt());
 9604        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9605
 9606        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9607        workspace.update_in(cx, |workspace, window, cx| {
 9608            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9609        });
 9610        item.update_in(cx, |item, _window, cx| {
 9611            item.is_dirty = true;
 9612            for project_item in &mut item.project_items {
 9613                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9614            }
 9615        });
 9616        cx.run_until_parked();
 9617        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9618
 9619        // Autosave on focus change, ensuring closing the tab counts as such.
 9620        item.update(cx, |item, cx| {
 9621            SettingsStore::update_global(cx, |settings, cx| {
 9622                settings.update_user_settings(cx, |settings| {
 9623                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9624                })
 9625            });
 9626            item.is_dirty = true;
 9627            for project_item in &mut item.project_items {
 9628                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9629            }
 9630        });
 9631
 9632        pane.update_in(cx, |pane, window, cx| {
 9633            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9634        })
 9635        .await
 9636        .unwrap();
 9637        assert!(!cx.has_pending_prompt());
 9638        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9639
 9640        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9641        workspace.update_in(cx, |workspace, window, cx| {
 9642            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9643        });
 9644        item.update_in(cx, |item, window, cx| {
 9645            item.project_items[0].update(cx, |item, _| {
 9646                item.entry_id = None;
 9647            });
 9648            item.is_dirty = true;
 9649            window.blur();
 9650        });
 9651        cx.run_until_parked();
 9652        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9653
 9654        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9655        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9656            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9657        });
 9658        cx.run_until_parked();
 9659        assert!(cx.has_pending_prompt());
 9660        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9661    }
 9662
 9663    #[gpui::test]
 9664    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9665        init_test(cx);
 9666
 9667        let fs = FakeFs::new(cx.executor());
 9668
 9669        let project = Project::test(fs, [], cx).await;
 9670        let (workspace, cx) =
 9671            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9672
 9673        let item = cx.new(|cx| {
 9674            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9675        });
 9676        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9677        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9678        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9679
 9680        workspace.update_in(cx, |workspace, window, cx| {
 9681            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9682            let toolbar_notification_count = toolbar_notify_count.clone();
 9683            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9684                *toolbar_notification_count.borrow_mut() += 1
 9685            })
 9686            .detach();
 9687        });
 9688
 9689        pane.read_with(cx, |pane, _| {
 9690            assert!(!pane.can_navigate_backward());
 9691            assert!(!pane.can_navigate_forward());
 9692        });
 9693
 9694        item.update_in(cx, |item, _, cx| {
 9695            item.set_state("one".to_string(), cx);
 9696        });
 9697
 9698        // Toolbar must be notified to re-render the navigation buttons
 9699        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9700
 9701        pane.read_with(cx, |pane, _| {
 9702            assert!(pane.can_navigate_backward());
 9703            assert!(!pane.can_navigate_forward());
 9704        });
 9705
 9706        workspace
 9707            .update_in(cx, |workspace, window, cx| {
 9708                workspace.go_back(pane.downgrade(), window, cx)
 9709            })
 9710            .await
 9711            .unwrap();
 9712
 9713        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9714        pane.read_with(cx, |pane, _| {
 9715            assert!(!pane.can_navigate_backward());
 9716            assert!(pane.can_navigate_forward());
 9717        });
 9718    }
 9719
 9720    #[gpui::test]
 9721    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9722        init_test(cx);
 9723        let fs = FakeFs::new(cx.executor());
 9724
 9725        let project = Project::test(fs, [], cx).await;
 9726        let (workspace, cx) =
 9727            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9728
 9729        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9730            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
 9731            workspace.add_panel(panel.clone(), window, cx);
 9732
 9733            workspace
 9734                .right_dock()
 9735                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9736
 9737            panel
 9738        });
 9739
 9740        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9741        pane.update_in(cx, |pane, window, cx| {
 9742            let item = cx.new(TestItem::new);
 9743            pane.add_item(Box::new(item), true, true, None, window, cx);
 9744        });
 9745
 9746        // Transfer focus from center to panel
 9747        workspace.update_in(cx, |workspace, window, cx| {
 9748            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9749        });
 9750
 9751        workspace.update_in(cx, |workspace, window, cx| {
 9752            assert!(workspace.right_dock().read(cx).is_open());
 9753            assert!(!panel.is_zoomed(window, cx));
 9754            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9755        });
 9756
 9757        // Transfer focus from panel to center
 9758        workspace.update_in(cx, |workspace, window, cx| {
 9759            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9760        });
 9761
 9762        workspace.update_in(cx, |workspace, window, cx| {
 9763            assert!(workspace.right_dock().read(cx).is_open());
 9764            assert!(!panel.is_zoomed(window, cx));
 9765            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9766        });
 9767
 9768        // Close the dock
 9769        workspace.update_in(cx, |workspace, window, cx| {
 9770            workspace.toggle_dock(DockPosition::Right, window, cx);
 9771        });
 9772
 9773        workspace.update_in(cx, |workspace, window, cx| {
 9774            assert!(!workspace.right_dock().read(cx).is_open());
 9775            assert!(!panel.is_zoomed(window, cx));
 9776            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9777        });
 9778
 9779        // Open the dock
 9780        workspace.update_in(cx, |workspace, window, cx| {
 9781            workspace.toggle_dock(DockPosition::Right, window, cx);
 9782        });
 9783
 9784        workspace.update_in(cx, |workspace, window, cx| {
 9785            assert!(workspace.right_dock().read(cx).is_open());
 9786            assert!(!panel.is_zoomed(window, cx));
 9787            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9788        });
 9789
 9790        // Focus and zoom panel
 9791        panel.update_in(cx, |panel, window, cx| {
 9792            cx.focus_self(window);
 9793            panel.set_zoomed(true, window, cx)
 9794        });
 9795
 9796        workspace.update_in(cx, |workspace, window, cx| {
 9797            assert!(workspace.right_dock().read(cx).is_open());
 9798            assert!(panel.is_zoomed(window, cx));
 9799            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9800        });
 9801
 9802        // Transfer focus to the center closes the dock
 9803        workspace.update_in(cx, |workspace, window, cx| {
 9804            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9805        });
 9806
 9807        workspace.update_in(cx, |workspace, window, cx| {
 9808            assert!(!workspace.right_dock().read(cx).is_open());
 9809            assert!(panel.is_zoomed(window, cx));
 9810            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9811        });
 9812
 9813        // Transferring focus back to the panel keeps it zoomed
 9814        workspace.update_in(cx, |workspace, window, cx| {
 9815            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9816        });
 9817
 9818        workspace.update_in(cx, |workspace, window, cx| {
 9819            assert!(workspace.right_dock().read(cx).is_open());
 9820            assert!(panel.is_zoomed(window, cx));
 9821            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9822        });
 9823
 9824        // Close the dock while it is zoomed
 9825        workspace.update_in(cx, |workspace, window, cx| {
 9826            workspace.toggle_dock(DockPosition::Right, window, cx)
 9827        });
 9828
 9829        workspace.update_in(cx, |workspace, window, cx| {
 9830            assert!(!workspace.right_dock().read(cx).is_open());
 9831            assert!(panel.is_zoomed(window, cx));
 9832            assert!(workspace.zoomed.is_none());
 9833            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9834        });
 9835
 9836        // Opening the dock, when it's zoomed, retains focus
 9837        workspace.update_in(cx, |workspace, window, cx| {
 9838            workspace.toggle_dock(DockPosition::Right, window, cx)
 9839        });
 9840
 9841        workspace.update_in(cx, |workspace, window, cx| {
 9842            assert!(workspace.right_dock().read(cx).is_open());
 9843            assert!(panel.is_zoomed(window, cx));
 9844            assert!(workspace.zoomed.is_some());
 9845            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9846        });
 9847
 9848        // Unzoom and close the panel, zoom the active pane.
 9849        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9850        workspace.update_in(cx, |workspace, window, cx| {
 9851            workspace.toggle_dock(DockPosition::Right, window, cx)
 9852        });
 9853        pane.update_in(cx, |pane, window, cx| {
 9854            pane.toggle_zoom(&Default::default(), window, cx)
 9855        });
 9856
 9857        // Opening a dock unzooms the pane.
 9858        workspace.update_in(cx, |workspace, window, cx| {
 9859            workspace.toggle_dock(DockPosition::Right, window, cx)
 9860        });
 9861        workspace.update_in(cx, |workspace, window, cx| {
 9862            let pane = pane.read(cx);
 9863            assert!(!pane.is_zoomed());
 9864            assert!(!pane.focus_handle(cx).is_focused(window));
 9865            assert!(workspace.right_dock().read(cx).is_open());
 9866            assert!(workspace.zoomed.is_none());
 9867        });
 9868    }
 9869
 9870    #[gpui::test]
 9871    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
 9872        init_test(cx);
 9873        let fs = FakeFs::new(cx.executor());
 9874
 9875        let project = Project::test(fs, [], cx).await;
 9876        let (workspace, cx) =
 9877            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9878
 9879        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
 9880            workspace.active_pane().clone()
 9881        });
 9882
 9883        // Add an item to the pane so it can be zoomed
 9884        workspace.update_in(cx, |workspace, window, cx| {
 9885            let item = cx.new(TestItem::new);
 9886            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
 9887        });
 9888
 9889        // Initially not zoomed
 9890        workspace.update_in(cx, |workspace, _window, cx| {
 9891            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
 9892            assert!(
 9893                workspace.zoomed.is_none(),
 9894                "Workspace should track no zoomed pane"
 9895            );
 9896            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
 9897        });
 9898
 9899        // Zoom In
 9900        pane.update_in(cx, |pane, window, cx| {
 9901            pane.zoom_in(&crate::ZoomIn, window, cx);
 9902        });
 9903
 9904        workspace.update_in(cx, |workspace, window, cx| {
 9905            assert!(
 9906                pane.read(cx).is_zoomed(),
 9907                "Pane should be zoomed after ZoomIn"
 9908            );
 9909            assert!(
 9910                workspace.zoomed.is_some(),
 9911                "Workspace should track the zoomed pane"
 9912            );
 9913            assert!(
 9914                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9915                "ZoomIn should focus the pane"
 9916            );
 9917        });
 9918
 9919        // Zoom In again is a no-op
 9920        pane.update_in(cx, |pane, window, cx| {
 9921            pane.zoom_in(&crate::ZoomIn, window, cx);
 9922        });
 9923
 9924        workspace.update_in(cx, |workspace, window, cx| {
 9925            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
 9926            assert!(
 9927                workspace.zoomed.is_some(),
 9928                "Workspace still tracks zoomed pane"
 9929            );
 9930            assert!(
 9931                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9932                "Pane remains focused after repeated ZoomIn"
 9933            );
 9934        });
 9935
 9936        // Zoom Out
 9937        pane.update_in(cx, |pane, window, cx| {
 9938            pane.zoom_out(&crate::ZoomOut, window, cx);
 9939        });
 9940
 9941        workspace.update_in(cx, |workspace, _window, cx| {
 9942            assert!(
 9943                !pane.read(cx).is_zoomed(),
 9944                "Pane should unzoom after ZoomOut"
 9945            );
 9946            assert!(
 9947                workspace.zoomed.is_none(),
 9948                "Workspace clears zoom tracking after ZoomOut"
 9949            );
 9950        });
 9951
 9952        // Zoom Out again is a no-op
 9953        pane.update_in(cx, |pane, window, cx| {
 9954            pane.zoom_out(&crate::ZoomOut, window, cx);
 9955        });
 9956
 9957        workspace.update_in(cx, |workspace, _window, cx| {
 9958            assert!(
 9959                !pane.read(cx).is_zoomed(),
 9960                "Second ZoomOut keeps pane unzoomed"
 9961            );
 9962            assert!(
 9963                workspace.zoomed.is_none(),
 9964                "Workspace remains without zoomed pane"
 9965            );
 9966        });
 9967    }
 9968
 9969    #[gpui::test]
 9970    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
 9971        init_test(cx);
 9972        let fs = FakeFs::new(cx.executor());
 9973
 9974        let project = Project::test(fs, [], cx).await;
 9975        let (workspace, cx) =
 9976            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9977        workspace.update_in(cx, |workspace, window, cx| {
 9978            // Open two docks
 9979            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9980            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9981
 9982            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9983            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9984
 9985            assert!(left_dock.read(cx).is_open());
 9986            assert!(right_dock.read(cx).is_open());
 9987        });
 9988
 9989        workspace.update_in(cx, |workspace, window, cx| {
 9990            // Toggle all docks - should close both
 9991            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9992
 9993            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9994            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9995            assert!(!left_dock.read(cx).is_open());
 9996            assert!(!right_dock.read(cx).is_open());
 9997        });
 9998
 9999        workspace.update_in(cx, |workspace, window, cx| {
10000            // Toggle again - should reopen both
10001            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10002
10003            let left_dock = workspace.dock_at_position(DockPosition::Left);
10004            let right_dock = workspace.dock_at_position(DockPosition::Right);
10005            assert!(left_dock.read(cx).is_open());
10006            assert!(right_dock.read(cx).is_open());
10007        });
10008    }
10009
10010    #[gpui::test]
10011    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10012        init_test(cx);
10013        let fs = FakeFs::new(cx.executor());
10014
10015        let project = Project::test(fs, [], cx).await;
10016        let (workspace, cx) =
10017            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10018        workspace.update_in(cx, |workspace, window, cx| {
10019            // Open two docks
10020            let left_dock = workspace.dock_at_position(DockPosition::Left);
10021            let right_dock = workspace.dock_at_position(DockPosition::Right);
10022
10023            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10024            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10025
10026            assert!(left_dock.read(cx).is_open());
10027            assert!(right_dock.read(cx).is_open());
10028        });
10029
10030        workspace.update_in(cx, |workspace, window, cx| {
10031            // Close them manually
10032            workspace.toggle_dock(DockPosition::Left, window, cx);
10033            workspace.toggle_dock(DockPosition::Right, window, cx);
10034
10035            let left_dock = workspace.dock_at_position(DockPosition::Left);
10036            let right_dock = workspace.dock_at_position(DockPosition::Right);
10037            assert!(!left_dock.read(cx).is_open());
10038            assert!(!right_dock.read(cx).is_open());
10039        });
10040
10041        workspace.update_in(cx, |workspace, window, cx| {
10042            // Toggle all docks - only last closed (right dock) should reopen
10043            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10044
10045            let left_dock = workspace.dock_at_position(DockPosition::Left);
10046            let right_dock = workspace.dock_at_position(DockPosition::Right);
10047            assert!(!left_dock.read(cx).is_open());
10048            assert!(right_dock.read(cx).is_open());
10049        });
10050    }
10051
10052    #[gpui::test]
10053    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10054        init_test(cx);
10055        let fs = FakeFs::new(cx.executor());
10056        let project = Project::test(fs, [], cx).await;
10057        let (workspace, cx) =
10058            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10059
10060        // Open two docks (left and right) with one panel each
10061        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10062            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10063            workspace.add_panel(left_panel.clone(), window, cx);
10064
10065            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10066            workspace.add_panel(right_panel.clone(), window, cx);
10067
10068            workspace.toggle_dock(DockPosition::Left, window, cx);
10069            workspace.toggle_dock(DockPosition::Right, window, cx);
10070
10071            // Verify initial state
10072            assert!(
10073                workspace.left_dock().read(cx).is_open(),
10074                "Left dock should be open"
10075            );
10076            assert_eq!(
10077                workspace
10078                    .left_dock()
10079                    .read(cx)
10080                    .visible_panel()
10081                    .unwrap()
10082                    .panel_id(),
10083                left_panel.panel_id(),
10084                "Left panel should be visible in left dock"
10085            );
10086            assert!(
10087                workspace.right_dock().read(cx).is_open(),
10088                "Right dock should be open"
10089            );
10090            assert_eq!(
10091                workspace
10092                    .right_dock()
10093                    .read(cx)
10094                    .visible_panel()
10095                    .unwrap()
10096                    .panel_id(),
10097                right_panel.panel_id(),
10098                "Right panel should be visible in right dock"
10099            );
10100            assert!(
10101                !workspace.bottom_dock().read(cx).is_open(),
10102                "Bottom dock should be closed"
10103            );
10104
10105            (left_panel, right_panel)
10106        });
10107
10108        // Focus the left panel and move it to the next position (bottom dock)
10109        workspace.update_in(cx, |workspace, window, cx| {
10110            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10111            assert!(
10112                left_panel.read(cx).focus_handle(cx).is_focused(window),
10113                "Left panel should be focused"
10114            );
10115        });
10116
10117        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10118
10119        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10120        workspace.update(cx, |workspace, cx| {
10121            assert!(
10122                !workspace.left_dock().read(cx).is_open(),
10123                "Left dock should be closed"
10124            );
10125            assert!(
10126                workspace.bottom_dock().read(cx).is_open(),
10127                "Bottom dock should now be open"
10128            );
10129            assert_eq!(
10130                left_panel.read(cx).position,
10131                DockPosition::Bottom,
10132                "Left panel should now be in the bottom dock"
10133            );
10134            assert_eq!(
10135                workspace
10136                    .bottom_dock()
10137                    .read(cx)
10138                    .visible_panel()
10139                    .unwrap()
10140                    .panel_id(),
10141                left_panel.panel_id(),
10142                "Left panel should be the visible panel in the bottom dock"
10143            );
10144        });
10145
10146        // Toggle all docks off
10147        workspace.update_in(cx, |workspace, window, cx| {
10148            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10149            assert!(
10150                !workspace.left_dock().read(cx).is_open(),
10151                "Left dock should be closed"
10152            );
10153            assert!(
10154                !workspace.right_dock().read(cx).is_open(),
10155                "Right dock should be closed"
10156            );
10157            assert!(
10158                !workspace.bottom_dock().read(cx).is_open(),
10159                "Bottom dock should be closed"
10160            );
10161        });
10162
10163        // Toggle all docks back on and verify positions are restored
10164        workspace.update_in(cx, |workspace, window, cx| {
10165            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10166            assert!(
10167                !workspace.left_dock().read(cx).is_open(),
10168                "Left dock should remain closed"
10169            );
10170            assert!(
10171                workspace.right_dock().read(cx).is_open(),
10172                "Right dock should remain open"
10173            );
10174            assert!(
10175                workspace.bottom_dock().read(cx).is_open(),
10176                "Bottom dock should remain open"
10177            );
10178            assert_eq!(
10179                left_panel.read(cx).position,
10180                DockPosition::Bottom,
10181                "Left panel should remain in the bottom dock"
10182            );
10183            assert_eq!(
10184                right_panel.read(cx).position,
10185                DockPosition::Right,
10186                "Right panel should remain in the right dock"
10187            );
10188            assert_eq!(
10189                workspace
10190                    .bottom_dock()
10191                    .read(cx)
10192                    .visible_panel()
10193                    .unwrap()
10194                    .panel_id(),
10195                left_panel.panel_id(),
10196                "Left panel should be the visible panel in the right dock"
10197            );
10198        });
10199    }
10200
10201    #[gpui::test]
10202    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10203        init_test(cx);
10204
10205        let fs = FakeFs::new(cx.executor());
10206
10207        let project = Project::test(fs, None, cx).await;
10208        let (workspace, cx) =
10209            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10210
10211        // Let's arrange the panes like this:
10212        //
10213        // +-----------------------+
10214        // |         top           |
10215        // +------+--------+-------+
10216        // | left | center | right |
10217        // +------+--------+-------+
10218        // |        bottom         |
10219        // +-----------------------+
10220
10221        let top_item = cx.new(|cx| {
10222            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10223        });
10224        let bottom_item = cx.new(|cx| {
10225            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10226        });
10227        let left_item = cx.new(|cx| {
10228            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10229        });
10230        let right_item = cx.new(|cx| {
10231            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10232        });
10233        let center_item = cx.new(|cx| {
10234            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10235        });
10236
10237        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10238            let top_pane_id = workspace.active_pane().entity_id();
10239            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10240            workspace.split_pane(
10241                workspace.active_pane().clone(),
10242                SplitDirection::Down,
10243                window,
10244                cx,
10245            );
10246            top_pane_id
10247        });
10248        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10249            let bottom_pane_id = workspace.active_pane().entity_id();
10250            workspace.add_item_to_active_pane(
10251                Box::new(bottom_item.clone()),
10252                None,
10253                false,
10254                window,
10255                cx,
10256            );
10257            workspace.split_pane(
10258                workspace.active_pane().clone(),
10259                SplitDirection::Up,
10260                window,
10261                cx,
10262            );
10263            bottom_pane_id
10264        });
10265        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10266            let left_pane_id = workspace.active_pane().entity_id();
10267            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10268            workspace.split_pane(
10269                workspace.active_pane().clone(),
10270                SplitDirection::Right,
10271                window,
10272                cx,
10273            );
10274            left_pane_id
10275        });
10276        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10277            let right_pane_id = workspace.active_pane().entity_id();
10278            workspace.add_item_to_active_pane(
10279                Box::new(right_item.clone()),
10280                None,
10281                false,
10282                window,
10283                cx,
10284            );
10285            workspace.split_pane(
10286                workspace.active_pane().clone(),
10287                SplitDirection::Left,
10288                window,
10289                cx,
10290            );
10291            right_pane_id
10292        });
10293        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10294            let center_pane_id = workspace.active_pane().entity_id();
10295            workspace.add_item_to_active_pane(
10296                Box::new(center_item.clone()),
10297                None,
10298                false,
10299                window,
10300                cx,
10301            );
10302            center_pane_id
10303        });
10304        cx.executor().run_until_parked();
10305
10306        workspace.update_in(cx, |workspace, window, cx| {
10307            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10308
10309            // Join into next from center pane into right
10310            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10311        });
10312
10313        workspace.update_in(cx, |workspace, window, cx| {
10314            let active_pane = workspace.active_pane();
10315            assert_eq!(right_pane_id, active_pane.entity_id());
10316            assert_eq!(2, active_pane.read(cx).items_len());
10317            let item_ids_in_pane =
10318                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10319            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10320            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10321
10322            // Join into next from right pane into bottom
10323            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10324        });
10325
10326        workspace.update_in(cx, |workspace, window, cx| {
10327            let active_pane = workspace.active_pane();
10328            assert_eq!(bottom_pane_id, active_pane.entity_id());
10329            assert_eq!(3, active_pane.read(cx).items_len());
10330            let item_ids_in_pane =
10331                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10332            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10333            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10334            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10335
10336            // Join into next from bottom pane into left
10337            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10338        });
10339
10340        workspace.update_in(cx, |workspace, window, cx| {
10341            let active_pane = workspace.active_pane();
10342            assert_eq!(left_pane_id, active_pane.entity_id());
10343            assert_eq!(4, active_pane.read(cx).items_len());
10344            let item_ids_in_pane =
10345                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10346            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10347            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10348            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10349            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10350
10351            // Join into next from left pane into top
10352            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10353        });
10354
10355        workspace.update_in(cx, |workspace, window, cx| {
10356            let active_pane = workspace.active_pane();
10357            assert_eq!(top_pane_id, active_pane.entity_id());
10358            assert_eq!(5, active_pane.read(cx).items_len());
10359            let item_ids_in_pane =
10360                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10361            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10362            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10363            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10364            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10365            assert!(item_ids_in_pane.contains(&top_item.item_id()));
10366
10367            // Single pane left: no-op
10368            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10369        });
10370
10371        workspace.update(cx, |workspace, _cx| {
10372            let active_pane = workspace.active_pane();
10373            assert_eq!(top_pane_id, active_pane.entity_id());
10374        });
10375    }
10376
10377    fn add_an_item_to_active_pane(
10378        cx: &mut VisualTestContext,
10379        workspace: &Entity<Workspace>,
10380        item_id: u64,
10381    ) -> Entity<TestItem> {
10382        let item = cx.new(|cx| {
10383            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10384                item_id,
10385                "item{item_id}.txt",
10386                cx,
10387            )])
10388        });
10389        workspace.update_in(cx, |workspace, window, cx| {
10390            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10391        });
10392        item
10393    }
10394
10395    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10396        workspace.update_in(cx, |workspace, window, cx| {
10397            workspace.split_pane(
10398                workspace.active_pane().clone(),
10399                SplitDirection::Right,
10400                window,
10401                cx,
10402            )
10403        })
10404    }
10405
10406    #[gpui::test]
10407    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10408        init_test(cx);
10409        let fs = FakeFs::new(cx.executor());
10410        let project = Project::test(fs, None, cx).await;
10411        let (workspace, cx) =
10412            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10413
10414        add_an_item_to_active_pane(cx, &workspace, 1);
10415        split_pane(cx, &workspace);
10416        add_an_item_to_active_pane(cx, &workspace, 2);
10417        split_pane(cx, &workspace); // empty pane
10418        split_pane(cx, &workspace);
10419        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10420
10421        cx.executor().run_until_parked();
10422
10423        workspace.update(cx, |workspace, cx| {
10424            let num_panes = workspace.panes().len();
10425            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10426            let active_item = workspace
10427                .active_pane()
10428                .read(cx)
10429                .active_item()
10430                .expect("item is in focus");
10431
10432            assert_eq!(num_panes, 4);
10433            assert_eq!(num_items_in_current_pane, 1);
10434            assert_eq!(active_item.item_id(), last_item.item_id());
10435        });
10436
10437        workspace.update_in(cx, |workspace, window, cx| {
10438            workspace.join_all_panes(window, cx);
10439        });
10440
10441        workspace.update(cx, |workspace, cx| {
10442            let num_panes = workspace.panes().len();
10443            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10444            let active_item = workspace
10445                .active_pane()
10446                .read(cx)
10447                .active_item()
10448                .expect("item is in focus");
10449
10450            assert_eq!(num_panes, 1);
10451            assert_eq!(num_items_in_current_pane, 3);
10452            assert_eq!(active_item.item_id(), last_item.item_id());
10453        });
10454    }
10455    struct TestModal(FocusHandle);
10456
10457    impl TestModal {
10458        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10459            Self(cx.focus_handle())
10460        }
10461    }
10462
10463    impl EventEmitter<DismissEvent> for TestModal {}
10464
10465    impl Focusable for TestModal {
10466        fn focus_handle(&self, _cx: &App) -> FocusHandle {
10467            self.0.clone()
10468        }
10469    }
10470
10471    impl ModalView for TestModal {}
10472
10473    impl Render for TestModal {
10474        fn render(
10475            &mut self,
10476            _window: &mut Window,
10477            _cx: &mut Context<TestModal>,
10478        ) -> impl IntoElement {
10479            div().track_focus(&self.0)
10480        }
10481    }
10482
10483    #[gpui::test]
10484    async fn test_panels(cx: &mut gpui::TestAppContext) {
10485        init_test(cx);
10486        let fs = FakeFs::new(cx.executor());
10487
10488        let project = Project::test(fs, [], cx).await;
10489        let (workspace, cx) =
10490            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10491
10492        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10493            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10494            workspace.add_panel(panel_1.clone(), window, cx);
10495            workspace.toggle_dock(DockPosition::Left, window, cx);
10496            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10497            workspace.add_panel(panel_2.clone(), window, cx);
10498            workspace.toggle_dock(DockPosition::Right, window, cx);
10499
10500            let left_dock = workspace.left_dock();
10501            assert_eq!(
10502                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10503                panel_1.panel_id()
10504            );
10505            assert_eq!(
10506                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10507                panel_1.size(window, cx)
10508            );
10509
10510            left_dock.update(cx, |left_dock, cx| {
10511                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10512            });
10513            assert_eq!(
10514                workspace
10515                    .right_dock()
10516                    .read(cx)
10517                    .visible_panel()
10518                    .unwrap()
10519                    .panel_id(),
10520                panel_2.panel_id(),
10521            );
10522
10523            (panel_1, panel_2)
10524        });
10525
10526        // Move panel_1 to the right
10527        panel_1.update_in(cx, |panel_1, window, cx| {
10528            panel_1.set_position(DockPosition::Right, window, cx)
10529        });
10530
10531        workspace.update_in(cx, |workspace, window, cx| {
10532            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10533            // Since it was the only panel on the left, the left dock should now be closed.
10534            assert!(!workspace.left_dock().read(cx).is_open());
10535            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10536            let right_dock = workspace.right_dock();
10537            assert_eq!(
10538                right_dock.read(cx).visible_panel().unwrap().panel_id(),
10539                panel_1.panel_id()
10540            );
10541            assert_eq!(
10542                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10543                px(1337.)
10544            );
10545
10546            // Now we move panel_2 to the left
10547            panel_2.set_position(DockPosition::Left, window, cx);
10548        });
10549
10550        workspace.update(cx, |workspace, cx| {
10551            // Since panel_2 was not visible on the right, we don't open the left dock.
10552            assert!(!workspace.left_dock().read(cx).is_open());
10553            // And the right dock is unaffected in its displaying of panel_1
10554            assert!(workspace.right_dock().read(cx).is_open());
10555            assert_eq!(
10556                workspace
10557                    .right_dock()
10558                    .read(cx)
10559                    .visible_panel()
10560                    .unwrap()
10561                    .panel_id(),
10562                panel_1.panel_id(),
10563            );
10564        });
10565
10566        // Move panel_1 back to the left
10567        panel_1.update_in(cx, |panel_1, window, cx| {
10568            panel_1.set_position(DockPosition::Left, window, cx)
10569        });
10570
10571        workspace.update_in(cx, |workspace, window, cx| {
10572            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10573            let left_dock = workspace.left_dock();
10574            assert!(left_dock.read(cx).is_open());
10575            assert_eq!(
10576                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10577                panel_1.panel_id()
10578            );
10579            assert_eq!(
10580                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10581                px(1337.)
10582            );
10583            // And the right dock should be closed as it no longer has any panels.
10584            assert!(!workspace.right_dock().read(cx).is_open());
10585
10586            // Now we move panel_1 to the bottom
10587            panel_1.set_position(DockPosition::Bottom, window, cx);
10588        });
10589
10590        workspace.update_in(cx, |workspace, window, cx| {
10591            // Since panel_1 was visible on the left, we close the left dock.
10592            assert!(!workspace.left_dock().read(cx).is_open());
10593            // The bottom dock is sized based on the panel's default size,
10594            // since the panel orientation changed from vertical to horizontal.
10595            let bottom_dock = workspace.bottom_dock();
10596            assert_eq!(
10597                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10598                panel_1.size(window, cx),
10599            );
10600            // Close bottom dock and move panel_1 back to the left.
10601            bottom_dock.update(cx, |bottom_dock, cx| {
10602                bottom_dock.set_open(false, window, cx)
10603            });
10604            panel_1.set_position(DockPosition::Left, window, cx);
10605        });
10606
10607        // Emit activated event on panel 1
10608        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10609
10610        // Now the left dock is open and panel_1 is active and focused.
10611        workspace.update_in(cx, |workspace, window, cx| {
10612            let left_dock = workspace.left_dock();
10613            assert!(left_dock.read(cx).is_open());
10614            assert_eq!(
10615                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10616                panel_1.panel_id(),
10617            );
10618            assert!(panel_1.focus_handle(cx).is_focused(window));
10619        });
10620
10621        // Emit closed event on panel 2, which is not active
10622        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10623
10624        // Wo don't close the left dock, because panel_2 wasn't the active panel
10625        workspace.update(cx, |workspace, cx| {
10626            let left_dock = workspace.left_dock();
10627            assert!(left_dock.read(cx).is_open());
10628            assert_eq!(
10629                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10630                panel_1.panel_id(),
10631            );
10632        });
10633
10634        // Emitting a ZoomIn event shows the panel as zoomed.
10635        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10636        workspace.read_with(cx, |workspace, _| {
10637            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10638            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10639        });
10640
10641        // Move panel to another dock while it is zoomed
10642        panel_1.update_in(cx, |panel, window, cx| {
10643            panel.set_position(DockPosition::Right, window, cx)
10644        });
10645        workspace.read_with(cx, |workspace, _| {
10646            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10647
10648            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10649        });
10650
10651        // This is a helper for getting a:
10652        // - valid focus on an element,
10653        // - that isn't a part of the panes and panels system of the Workspace,
10654        // - and doesn't trigger the 'on_focus_lost' API.
10655        let focus_other_view = {
10656            let workspace = workspace.clone();
10657            move |cx: &mut VisualTestContext| {
10658                workspace.update_in(cx, |workspace, window, cx| {
10659                    if workspace.active_modal::<TestModal>(cx).is_some() {
10660                        workspace.toggle_modal(window, cx, TestModal::new);
10661                        workspace.toggle_modal(window, cx, TestModal::new);
10662                    } else {
10663                        workspace.toggle_modal(window, cx, TestModal::new);
10664                    }
10665                })
10666            }
10667        };
10668
10669        // If focus is transferred to another view that's not a panel or another pane, we still show
10670        // the panel as zoomed.
10671        focus_other_view(cx);
10672        workspace.read_with(cx, |workspace, _| {
10673            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10674            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10675        });
10676
10677        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10678        workspace.update_in(cx, |_workspace, window, cx| {
10679            cx.focus_self(window);
10680        });
10681        workspace.read_with(cx, |workspace, _| {
10682            assert_eq!(workspace.zoomed, None);
10683            assert_eq!(workspace.zoomed_position, None);
10684        });
10685
10686        // If focus is transferred again to another view that's not a panel or a pane, we won't
10687        // show the panel as zoomed because it wasn't zoomed before.
10688        focus_other_view(cx);
10689        workspace.read_with(cx, |workspace, _| {
10690            assert_eq!(workspace.zoomed, None);
10691            assert_eq!(workspace.zoomed_position, None);
10692        });
10693
10694        // When the panel is activated, it is zoomed again.
10695        cx.dispatch_action(ToggleRightDock);
10696        workspace.read_with(cx, |workspace, _| {
10697            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10698            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10699        });
10700
10701        // Emitting a ZoomOut event unzooms the panel.
10702        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10703        workspace.read_with(cx, |workspace, _| {
10704            assert_eq!(workspace.zoomed, None);
10705            assert_eq!(workspace.zoomed_position, None);
10706        });
10707
10708        // Emit closed event on panel 1, which is active
10709        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10710
10711        // Now the left dock is closed, because panel_1 was the active panel
10712        workspace.update(cx, |workspace, cx| {
10713            let right_dock = workspace.right_dock();
10714            assert!(!right_dock.read(cx).is_open());
10715        });
10716    }
10717
10718    #[gpui::test]
10719    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10720        init_test(cx);
10721
10722        let fs = FakeFs::new(cx.background_executor.clone());
10723        let project = Project::test(fs, [], cx).await;
10724        let (workspace, cx) =
10725            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10726        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10727
10728        let dirty_regular_buffer = cx.new(|cx| {
10729            TestItem::new(cx)
10730                .with_dirty(true)
10731                .with_label("1.txt")
10732                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10733        });
10734        let dirty_regular_buffer_2 = cx.new(|cx| {
10735            TestItem::new(cx)
10736                .with_dirty(true)
10737                .with_label("2.txt")
10738                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10739        });
10740        let dirty_multi_buffer_with_both = cx.new(|cx| {
10741            TestItem::new(cx)
10742                .with_dirty(true)
10743                .with_buffer_kind(ItemBufferKind::Multibuffer)
10744                .with_label("Fake Project Search")
10745                .with_project_items(&[
10746                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10747                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10748                ])
10749        });
10750        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10751        workspace.update_in(cx, |workspace, window, cx| {
10752            workspace.add_item(
10753                pane.clone(),
10754                Box::new(dirty_regular_buffer.clone()),
10755                None,
10756                false,
10757                false,
10758                window,
10759                cx,
10760            );
10761            workspace.add_item(
10762                pane.clone(),
10763                Box::new(dirty_regular_buffer_2.clone()),
10764                None,
10765                false,
10766                false,
10767                window,
10768                cx,
10769            );
10770            workspace.add_item(
10771                pane.clone(),
10772                Box::new(dirty_multi_buffer_with_both.clone()),
10773                None,
10774                false,
10775                false,
10776                window,
10777                cx,
10778            );
10779        });
10780
10781        pane.update_in(cx, |pane, window, cx| {
10782            pane.activate_item(2, true, true, window, cx);
10783            assert_eq!(
10784                pane.active_item().unwrap().item_id(),
10785                multi_buffer_with_both_files_id,
10786                "Should select the multi buffer in the pane"
10787            );
10788        });
10789        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10790            pane.close_other_items(
10791                &CloseOtherItems {
10792                    save_intent: Some(SaveIntent::Save),
10793                    close_pinned: true,
10794                },
10795                None,
10796                window,
10797                cx,
10798            )
10799        });
10800        cx.background_executor.run_until_parked();
10801        assert!(!cx.has_pending_prompt());
10802        close_all_but_multi_buffer_task
10803            .await
10804            .expect("Closing all buffers but the multi buffer failed");
10805        pane.update(cx, |pane, cx| {
10806            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10807            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10808            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10809            assert_eq!(pane.items_len(), 1);
10810            assert_eq!(
10811                pane.active_item().unwrap().item_id(),
10812                multi_buffer_with_both_files_id,
10813                "Should have only the multi buffer left in the pane"
10814            );
10815            assert!(
10816                dirty_multi_buffer_with_both.read(cx).is_dirty,
10817                "The multi buffer containing the unsaved buffer should still be dirty"
10818            );
10819        });
10820
10821        dirty_regular_buffer.update(cx, |buffer, cx| {
10822            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10823        });
10824
10825        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10826            pane.close_active_item(
10827                &CloseActiveItem {
10828                    save_intent: Some(SaveIntent::Close),
10829                    close_pinned: false,
10830                },
10831                window,
10832                cx,
10833            )
10834        });
10835        cx.background_executor.run_until_parked();
10836        assert!(
10837            cx.has_pending_prompt(),
10838            "Dirty multi buffer should prompt a save dialog"
10839        );
10840        cx.simulate_prompt_answer("Save");
10841        cx.background_executor.run_until_parked();
10842        close_multi_buffer_task
10843            .await
10844            .expect("Closing the multi buffer failed");
10845        pane.update(cx, |pane, cx| {
10846            assert_eq!(
10847                dirty_multi_buffer_with_both.read(cx).save_count,
10848                1,
10849                "Multi buffer item should get be saved"
10850            );
10851            // Test impl does not save inner items, so we do not assert them
10852            assert_eq!(
10853                pane.items_len(),
10854                0,
10855                "No more items should be left in the pane"
10856            );
10857            assert!(pane.active_item().is_none());
10858        });
10859    }
10860
10861    #[gpui::test]
10862    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10863        cx: &mut TestAppContext,
10864    ) {
10865        init_test(cx);
10866
10867        let fs = FakeFs::new(cx.background_executor.clone());
10868        let project = Project::test(fs, [], cx).await;
10869        let (workspace, cx) =
10870            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10871        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10872
10873        let dirty_regular_buffer = cx.new(|cx| {
10874            TestItem::new(cx)
10875                .with_dirty(true)
10876                .with_label("1.txt")
10877                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10878        });
10879        let dirty_regular_buffer_2 = cx.new(|cx| {
10880            TestItem::new(cx)
10881                .with_dirty(true)
10882                .with_label("2.txt")
10883                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10884        });
10885        let clear_regular_buffer = cx.new(|cx| {
10886            TestItem::new(cx)
10887                .with_label("3.txt")
10888                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10889        });
10890
10891        let dirty_multi_buffer_with_both = cx.new(|cx| {
10892            TestItem::new(cx)
10893                .with_dirty(true)
10894                .with_buffer_kind(ItemBufferKind::Multibuffer)
10895                .with_label("Fake Project Search")
10896                .with_project_items(&[
10897                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10898                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10899                    clear_regular_buffer.read(cx).project_items[0].clone(),
10900                ])
10901        });
10902        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10903        workspace.update_in(cx, |workspace, window, cx| {
10904            workspace.add_item(
10905                pane.clone(),
10906                Box::new(dirty_regular_buffer.clone()),
10907                None,
10908                false,
10909                false,
10910                window,
10911                cx,
10912            );
10913            workspace.add_item(
10914                pane.clone(),
10915                Box::new(dirty_multi_buffer_with_both.clone()),
10916                None,
10917                false,
10918                false,
10919                window,
10920                cx,
10921            );
10922        });
10923
10924        pane.update_in(cx, |pane, window, cx| {
10925            pane.activate_item(1, true, true, window, cx);
10926            assert_eq!(
10927                pane.active_item().unwrap().item_id(),
10928                multi_buffer_with_both_files_id,
10929                "Should select the multi buffer in the pane"
10930            );
10931        });
10932        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10933            pane.close_active_item(
10934                &CloseActiveItem {
10935                    save_intent: None,
10936                    close_pinned: false,
10937                },
10938                window,
10939                cx,
10940            )
10941        });
10942        cx.background_executor.run_until_parked();
10943        assert!(
10944            cx.has_pending_prompt(),
10945            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10946        );
10947    }
10948
10949    /// Tests that when `close_on_file_delete` is enabled, files are automatically
10950    /// closed when they are deleted from disk.
10951    #[gpui::test]
10952    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10953        init_test(cx);
10954
10955        // Enable the close_on_disk_deletion setting
10956        cx.update_global(|store: &mut SettingsStore, cx| {
10957            store.update_user_settings(cx, |settings| {
10958                settings.workspace.close_on_file_delete = Some(true);
10959            });
10960        });
10961
10962        let fs = FakeFs::new(cx.background_executor.clone());
10963        let project = Project::test(fs, [], cx).await;
10964        let (workspace, cx) =
10965            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10966        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10967
10968        // Create a test item that simulates a file
10969        let item = cx.new(|cx| {
10970            TestItem::new(cx)
10971                .with_label("test.txt")
10972                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10973        });
10974
10975        // Add item to workspace
10976        workspace.update_in(cx, |workspace, window, cx| {
10977            workspace.add_item(
10978                pane.clone(),
10979                Box::new(item.clone()),
10980                None,
10981                false,
10982                false,
10983                window,
10984                cx,
10985            );
10986        });
10987
10988        // Verify the item is in the pane
10989        pane.read_with(cx, |pane, _| {
10990            assert_eq!(pane.items().count(), 1);
10991        });
10992
10993        // Simulate file deletion by setting the item's deleted state
10994        item.update(cx, |item, _| {
10995            item.set_has_deleted_file(true);
10996        });
10997
10998        // Emit UpdateTab event to trigger the close behavior
10999        cx.run_until_parked();
11000        item.update(cx, |_, cx| {
11001            cx.emit(ItemEvent::UpdateTab);
11002        });
11003
11004        // Allow the close operation to complete
11005        cx.run_until_parked();
11006
11007        // Verify the item was automatically closed
11008        pane.read_with(cx, |pane, _| {
11009            assert_eq!(
11010                pane.items().count(),
11011                0,
11012                "Item should be automatically closed when file is deleted"
11013            );
11014        });
11015    }
11016
11017    /// Tests that when `close_on_file_delete` is disabled (default), files remain
11018    /// open with a strikethrough when they are deleted from disk.
11019    #[gpui::test]
11020    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11021        init_test(cx);
11022
11023        // Ensure close_on_disk_deletion is disabled (default)
11024        cx.update_global(|store: &mut SettingsStore, cx| {
11025            store.update_user_settings(cx, |settings| {
11026                settings.workspace.close_on_file_delete = Some(false);
11027            });
11028        });
11029
11030        let fs = FakeFs::new(cx.background_executor.clone());
11031        let project = Project::test(fs, [], cx).await;
11032        let (workspace, cx) =
11033            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11034        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11035
11036        // Create a test item that simulates a file
11037        let item = cx.new(|cx| {
11038            TestItem::new(cx)
11039                .with_label("test.txt")
11040                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11041        });
11042
11043        // Add item to workspace
11044        workspace.update_in(cx, |workspace, window, cx| {
11045            workspace.add_item(
11046                pane.clone(),
11047                Box::new(item.clone()),
11048                None,
11049                false,
11050                false,
11051                window,
11052                cx,
11053            );
11054        });
11055
11056        // Verify the item is in the pane
11057        pane.read_with(cx, |pane, _| {
11058            assert_eq!(pane.items().count(), 1);
11059        });
11060
11061        // Simulate file deletion
11062        item.update(cx, |item, _| {
11063            item.set_has_deleted_file(true);
11064        });
11065
11066        // Emit UpdateTab event
11067        cx.run_until_parked();
11068        item.update(cx, |_, cx| {
11069            cx.emit(ItemEvent::UpdateTab);
11070        });
11071
11072        // Allow any potential close operation to complete
11073        cx.run_until_parked();
11074
11075        // Verify the item remains open (with strikethrough)
11076        pane.read_with(cx, |pane, _| {
11077            assert_eq!(
11078                pane.items().count(),
11079                1,
11080                "Item should remain open when close_on_disk_deletion is disabled"
11081            );
11082        });
11083
11084        // Verify the item shows as deleted
11085        item.read_with(cx, |item, _| {
11086            assert!(
11087                item.has_deleted_file,
11088                "Item should be marked as having deleted file"
11089            );
11090        });
11091    }
11092
11093    /// Tests that dirty files are not automatically closed when deleted from disk,
11094    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11095    /// unsaved changes without being prompted.
11096    #[gpui::test]
11097    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11098        init_test(cx);
11099
11100        // Enable the close_on_file_delete setting
11101        cx.update_global(|store: &mut SettingsStore, cx| {
11102            store.update_user_settings(cx, |settings| {
11103                settings.workspace.close_on_file_delete = Some(true);
11104            });
11105        });
11106
11107        let fs = FakeFs::new(cx.background_executor.clone());
11108        let project = Project::test(fs, [], cx).await;
11109        let (workspace, cx) =
11110            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11111        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11112
11113        // Create a dirty test item
11114        let item = cx.new(|cx| {
11115            TestItem::new(cx)
11116                .with_dirty(true)
11117                .with_label("test.txt")
11118                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11119        });
11120
11121        // Add item to workspace
11122        workspace.update_in(cx, |workspace, window, cx| {
11123            workspace.add_item(
11124                pane.clone(),
11125                Box::new(item.clone()),
11126                None,
11127                false,
11128                false,
11129                window,
11130                cx,
11131            );
11132        });
11133
11134        // Simulate file deletion
11135        item.update(cx, |item, _| {
11136            item.set_has_deleted_file(true);
11137        });
11138
11139        // Emit UpdateTab event to trigger the close behavior
11140        cx.run_until_parked();
11141        item.update(cx, |_, cx| {
11142            cx.emit(ItemEvent::UpdateTab);
11143        });
11144
11145        // Allow any potential close operation to complete
11146        cx.run_until_parked();
11147
11148        // Verify the item remains open (dirty files are not auto-closed)
11149        pane.read_with(cx, |pane, _| {
11150            assert_eq!(
11151                pane.items().count(),
11152                1,
11153                "Dirty items should not be automatically closed even when file is deleted"
11154            );
11155        });
11156
11157        // Verify the item is marked as deleted and still dirty
11158        item.read_with(cx, |item, _| {
11159            assert!(
11160                item.has_deleted_file,
11161                "Item should be marked as having deleted file"
11162            );
11163            assert!(item.is_dirty, "Item should still be dirty");
11164        });
11165    }
11166
11167    /// Tests that navigation history is cleaned up when files are auto-closed
11168    /// due to deletion from disk.
11169    #[gpui::test]
11170    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11171        init_test(cx);
11172
11173        // Enable the close_on_file_delete setting
11174        cx.update_global(|store: &mut SettingsStore, cx| {
11175            store.update_user_settings(cx, |settings| {
11176                settings.workspace.close_on_file_delete = Some(true);
11177            });
11178        });
11179
11180        let fs = FakeFs::new(cx.background_executor.clone());
11181        let project = Project::test(fs, [], cx).await;
11182        let (workspace, cx) =
11183            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11184        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11185
11186        // Create test items
11187        let item1 = cx.new(|cx| {
11188            TestItem::new(cx)
11189                .with_label("test1.txt")
11190                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11191        });
11192        let item1_id = item1.item_id();
11193
11194        let item2 = cx.new(|cx| {
11195            TestItem::new(cx)
11196                .with_label("test2.txt")
11197                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11198        });
11199
11200        // Add items to workspace
11201        workspace.update_in(cx, |workspace, window, cx| {
11202            workspace.add_item(
11203                pane.clone(),
11204                Box::new(item1.clone()),
11205                None,
11206                false,
11207                false,
11208                window,
11209                cx,
11210            );
11211            workspace.add_item(
11212                pane.clone(),
11213                Box::new(item2.clone()),
11214                None,
11215                false,
11216                false,
11217                window,
11218                cx,
11219            );
11220        });
11221
11222        // Activate item1 to ensure it gets navigation entries
11223        pane.update_in(cx, |pane, window, cx| {
11224            pane.activate_item(0, true, true, window, cx);
11225        });
11226
11227        // Switch to item2 and back to create navigation history
11228        pane.update_in(cx, |pane, window, cx| {
11229            pane.activate_item(1, true, true, window, cx);
11230        });
11231        cx.run_until_parked();
11232
11233        pane.update_in(cx, |pane, window, cx| {
11234            pane.activate_item(0, true, true, window, cx);
11235        });
11236        cx.run_until_parked();
11237
11238        // Simulate file deletion for item1
11239        item1.update(cx, |item, _| {
11240            item.set_has_deleted_file(true);
11241        });
11242
11243        // Emit UpdateTab event to trigger the close behavior
11244        item1.update(cx, |_, cx| {
11245            cx.emit(ItemEvent::UpdateTab);
11246        });
11247        cx.run_until_parked();
11248
11249        // Verify item1 was closed
11250        pane.read_with(cx, |pane, _| {
11251            assert_eq!(
11252                pane.items().count(),
11253                1,
11254                "Should have 1 item remaining after auto-close"
11255            );
11256        });
11257
11258        // Check navigation history after close
11259        let has_item = pane.read_with(cx, |pane, cx| {
11260            let mut has_item = false;
11261            pane.nav_history().for_each_entry(cx, |entry, _| {
11262                if entry.item.id() == item1_id {
11263                    has_item = true;
11264                }
11265            });
11266            has_item
11267        });
11268
11269        assert!(
11270            !has_item,
11271            "Navigation history should not contain closed item entries"
11272        );
11273    }
11274
11275    #[gpui::test]
11276    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11277        cx: &mut TestAppContext,
11278    ) {
11279        init_test(cx);
11280
11281        let fs = FakeFs::new(cx.background_executor.clone());
11282        let project = Project::test(fs, [], cx).await;
11283        let (workspace, cx) =
11284            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11285        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11286
11287        let dirty_regular_buffer = cx.new(|cx| {
11288            TestItem::new(cx)
11289                .with_dirty(true)
11290                .with_label("1.txt")
11291                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11292        });
11293        let dirty_regular_buffer_2 = cx.new(|cx| {
11294            TestItem::new(cx)
11295                .with_dirty(true)
11296                .with_label("2.txt")
11297                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11298        });
11299        let clear_regular_buffer = cx.new(|cx| {
11300            TestItem::new(cx)
11301                .with_label("3.txt")
11302                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11303        });
11304
11305        let dirty_multi_buffer = cx.new(|cx| {
11306            TestItem::new(cx)
11307                .with_dirty(true)
11308                .with_buffer_kind(ItemBufferKind::Multibuffer)
11309                .with_label("Fake Project Search")
11310                .with_project_items(&[
11311                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11312                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11313                    clear_regular_buffer.read(cx).project_items[0].clone(),
11314                ])
11315        });
11316        workspace.update_in(cx, |workspace, window, cx| {
11317            workspace.add_item(
11318                pane.clone(),
11319                Box::new(dirty_regular_buffer.clone()),
11320                None,
11321                false,
11322                false,
11323                window,
11324                cx,
11325            );
11326            workspace.add_item(
11327                pane.clone(),
11328                Box::new(dirty_regular_buffer_2.clone()),
11329                None,
11330                false,
11331                false,
11332                window,
11333                cx,
11334            );
11335            workspace.add_item(
11336                pane.clone(),
11337                Box::new(dirty_multi_buffer.clone()),
11338                None,
11339                false,
11340                false,
11341                window,
11342                cx,
11343            );
11344        });
11345
11346        pane.update_in(cx, |pane, window, cx| {
11347            pane.activate_item(2, true, true, window, cx);
11348            assert_eq!(
11349                pane.active_item().unwrap().item_id(),
11350                dirty_multi_buffer.item_id(),
11351                "Should select the multi buffer in the pane"
11352            );
11353        });
11354        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11355            pane.close_active_item(
11356                &CloseActiveItem {
11357                    save_intent: None,
11358                    close_pinned: false,
11359                },
11360                window,
11361                cx,
11362            )
11363        });
11364        cx.background_executor.run_until_parked();
11365        assert!(
11366            !cx.has_pending_prompt(),
11367            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11368        );
11369        close_multi_buffer_task
11370            .await
11371            .expect("Closing multi buffer failed");
11372        pane.update(cx, |pane, cx| {
11373            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11374            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11375            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11376            assert_eq!(
11377                pane.items()
11378                    .map(|item| item.item_id())
11379                    .sorted()
11380                    .collect::<Vec<_>>(),
11381                vec![
11382                    dirty_regular_buffer.item_id(),
11383                    dirty_regular_buffer_2.item_id(),
11384                ],
11385                "Should have no multi buffer left in the pane"
11386            );
11387            assert!(dirty_regular_buffer.read(cx).is_dirty);
11388            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11389        });
11390    }
11391
11392    #[gpui::test]
11393    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11394        init_test(cx);
11395        let fs = FakeFs::new(cx.executor());
11396        let project = Project::test(fs, [], cx).await;
11397        let (workspace, cx) =
11398            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11399
11400        // Add a new panel to the right dock, opening the dock and setting the
11401        // focus to the new panel.
11402        let panel = workspace.update_in(cx, |workspace, window, cx| {
11403            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11404            workspace.add_panel(panel.clone(), window, cx);
11405
11406            workspace
11407                .right_dock()
11408                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11409
11410            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11411
11412            panel
11413        });
11414
11415        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11416        // panel to the next valid position which, in this case, is the left
11417        // dock.
11418        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11419        workspace.update(cx, |workspace, cx| {
11420            assert!(workspace.left_dock().read(cx).is_open());
11421            assert_eq!(panel.read(cx).position, DockPosition::Left);
11422        });
11423
11424        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11425        // panel to the next valid position which, in this case, is the bottom
11426        // dock.
11427        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11428        workspace.update(cx, |workspace, cx| {
11429            assert!(workspace.bottom_dock().read(cx).is_open());
11430            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11431        });
11432
11433        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11434        // around moving the panel to its initial position, the right dock.
11435        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11436        workspace.update(cx, |workspace, cx| {
11437            assert!(workspace.right_dock().read(cx).is_open());
11438            assert_eq!(panel.read(cx).position, DockPosition::Right);
11439        });
11440
11441        // Remove focus from the panel, ensuring that, if the panel is not
11442        // focused, the `MoveFocusedPanelToNextPosition` action does not update
11443        // the panel's position, so the panel is still in the right dock.
11444        workspace.update_in(cx, |workspace, window, cx| {
11445            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11446        });
11447
11448        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11449        workspace.update(cx, |workspace, cx| {
11450            assert!(workspace.right_dock().read(cx).is_open());
11451            assert_eq!(panel.read(cx).position, DockPosition::Right);
11452        });
11453    }
11454
11455    #[gpui::test]
11456    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11457        init_test(cx);
11458
11459        let fs = FakeFs::new(cx.executor());
11460        let project = Project::test(fs, [], cx).await;
11461        let (workspace, cx) =
11462            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11463
11464        let item_1 = cx.new(|cx| {
11465            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11466        });
11467        workspace.update_in(cx, |workspace, window, cx| {
11468            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11469            workspace.move_item_to_pane_in_direction(
11470                &MoveItemToPaneInDirection {
11471                    direction: SplitDirection::Right,
11472                    focus: true,
11473                    clone: false,
11474                },
11475                window,
11476                cx,
11477            );
11478            workspace.move_item_to_pane_at_index(
11479                &MoveItemToPane {
11480                    destination: 3,
11481                    focus: true,
11482                    clone: false,
11483                },
11484                window,
11485                cx,
11486            );
11487
11488            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11489            assert_eq!(
11490                pane_items_paths(&workspace.active_pane, cx),
11491                vec!["first.txt".to_string()],
11492                "Single item was not moved anywhere"
11493            );
11494        });
11495
11496        let item_2 = cx.new(|cx| {
11497            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11498        });
11499        workspace.update_in(cx, |workspace, window, cx| {
11500            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11501            assert_eq!(
11502                pane_items_paths(&workspace.panes[0], cx),
11503                vec!["first.txt".to_string(), "second.txt".to_string()],
11504            );
11505            workspace.move_item_to_pane_in_direction(
11506                &MoveItemToPaneInDirection {
11507                    direction: SplitDirection::Right,
11508                    focus: true,
11509                    clone: false,
11510                },
11511                window,
11512                cx,
11513            );
11514
11515            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11516            assert_eq!(
11517                pane_items_paths(&workspace.panes[0], cx),
11518                vec!["first.txt".to_string()],
11519                "After moving, one item should be left in the original pane"
11520            );
11521            assert_eq!(
11522                pane_items_paths(&workspace.panes[1], cx),
11523                vec!["second.txt".to_string()],
11524                "New item should have been moved to the new pane"
11525            );
11526        });
11527
11528        let item_3 = cx.new(|cx| {
11529            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11530        });
11531        workspace.update_in(cx, |workspace, window, cx| {
11532            let original_pane = workspace.panes[0].clone();
11533            workspace.set_active_pane(&original_pane, window, cx);
11534            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11535            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11536            assert_eq!(
11537                pane_items_paths(&workspace.active_pane, cx),
11538                vec!["first.txt".to_string(), "third.txt".to_string()],
11539                "New pane should be ready to move one item out"
11540            );
11541
11542            workspace.move_item_to_pane_at_index(
11543                &MoveItemToPane {
11544                    destination: 3,
11545                    focus: true,
11546                    clone: false,
11547                },
11548                window,
11549                cx,
11550            );
11551            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11552            assert_eq!(
11553                pane_items_paths(&workspace.active_pane, cx),
11554                vec!["first.txt".to_string()],
11555                "After moving, one item should be left in the original pane"
11556            );
11557            assert_eq!(
11558                pane_items_paths(&workspace.panes[1], cx),
11559                vec!["second.txt".to_string()],
11560                "Previously created pane should be unchanged"
11561            );
11562            assert_eq!(
11563                pane_items_paths(&workspace.panes[2], cx),
11564                vec!["third.txt".to_string()],
11565                "New item should have been moved to the new pane"
11566            );
11567        });
11568    }
11569
11570    #[gpui::test]
11571    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11572        init_test(cx);
11573
11574        let fs = FakeFs::new(cx.executor());
11575        let project = Project::test(fs, [], cx).await;
11576        let (workspace, cx) =
11577            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11578
11579        let item_1 = cx.new(|cx| {
11580            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11581        });
11582        workspace.update_in(cx, |workspace, window, cx| {
11583            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11584            workspace.move_item_to_pane_in_direction(
11585                &MoveItemToPaneInDirection {
11586                    direction: SplitDirection::Right,
11587                    focus: true,
11588                    clone: true,
11589                },
11590                window,
11591                cx,
11592            );
11593            workspace.move_item_to_pane_at_index(
11594                &MoveItemToPane {
11595                    destination: 3,
11596                    focus: true,
11597                    clone: true,
11598                },
11599                window,
11600                cx,
11601            );
11602        });
11603        cx.run_until_parked();
11604
11605        workspace.update(cx, |workspace, cx| {
11606            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11607            for pane in workspace.panes() {
11608                assert_eq!(
11609                    pane_items_paths(pane, cx),
11610                    vec!["first.txt".to_string()],
11611                    "Single item exists in all panes"
11612                );
11613            }
11614        });
11615
11616        // verify that the active pane has been updated after waiting for the
11617        // pane focus event to fire and resolve
11618        workspace.read_with(cx, |workspace, _app| {
11619            assert_eq!(
11620                workspace.active_pane(),
11621                &workspace.panes[2],
11622                "The third pane should be the active one: {:?}",
11623                workspace.panes
11624            );
11625        })
11626    }
11627
11628    mod register_project_item_tests {
11629
11630        use super::*;
11631
11632        // View
11633        struct TestPngItemView {
11634            focus_handle: FocusHandle,
11635        }
11636        // Model
11637        struct TestPngItem {}
11638
11639        impl project::ProjectItem for TestPngItem {
11640            fn try_open(
11641                _project: &Entity<Project>,
11642                path: &ProjectPath,
11643                cx: &mut App,
11644            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11645                if path.path.extension().unwrap() == "png" {
11646                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11647                } else {
11648                    None
11649                }
11650            }
11651
11652            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11653                None
11654            }
11655
11656            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11657                None
11658            }
11659
11660            fn is_dirty(&self) -> bool {
11661                false
11662            }
11663        }
11664
11665        impl Item for TestPngItemView {
11666            type Event = ();
11667            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11668                "".into()
11669            }
11670        }
11671        impl EventEmitter<()> for TestPngItemView {}
11672        impl Focusable for TestPngItemView {
11673            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11674                self.focus_handle.clone()
11675            }
11676        }
11677
11678        impl Render for TestPngItemView {
11679            fn render(
11680                &mut self,
11681                _window: &mut Window,
11682                _cx: &mut Context<Self>,
11683            ) -> impl IntoElement {
11684                Empty
11685            }
11686        }
11687
11688        impl ProjectItem for TestPngItemView {
11689            type Item = TestPngItem;
11690
11691            fn for_project_item(
11692                _project: Entity<Project>,
11693                _pane: Option<&Pane>,
11694                _item: Entity<Self::Item>,
11695                _: &mut Window,
11696                cx: &mut Context<Self>,
11697            ) -> Self
11698            where
11699                Self: Sized,
11700            {
11701                Self {
11702                    focus_handle: cx.focus_handle(),
11703                }
11704            }
11705        }
11706
11707        // View
11708        struct TestIpynbItemView {
11709            focus_handle: FocusHandle,
11710        }
11711        // Model
11712        struct TestIpynbItem {}
11713
11714        impl project::ProjectItem for TestIpynbItem {
11715            fn try_open(
11716                _project: &Entity<Project>,
11717                path: &ProjectPath,
11718                cx: &mut App,
11719            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11720                if path.path.extension().unwrap() == "ipynb" {
11721                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11722                } else {
11723                    None
11724                }
11725            }
11726
11727            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11728                None
11729            }
11730
11731            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11732                None
11733            }
11734
11735            fn is_dirty(&self) -> bool {
11736                false
11737            }
11738        }
11739
11740        impl Item for TestIpynbItemView {
11741            type Event = ();
11742            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11743                "".into()
11744            }
11745        }
11746        impl EventEmitter<()> for TestIpynbItemView {}
11747        impl Focusable for TestIpynbItemView {
11748            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11749                self.focus_handle.clone()
11750            }
11751        }
11752
11753        impl Render for TestIpynbItemView {
11754            fn render(
11755                &mut self,
11756                _window: &mut Window,
11757                _cx: &mut Context<Self>,
11758            ) -> impl IntoElement {
11759                Empty
11760            }
11761        }
11762
11763        impl ProjectItem for TestIpynbItemView {
11764            type Item = TestIpynbItem;
11765
11766            fn for_project_item(
11767                _project: Entity<Project>,
11768                _pane: Option<&Pane>,
11769                _item: Entity<Self::Item>,
11770                _: &mut Window,
11771                cx: &mut Context<Self>,
11772            ) -> Self
11773            where
11774                Self: Sized,
11775            {
11776                Self {
11777                    focus_handle: cx.focus_handle(),
11778                }
11779            }
11780        }
11781
11782        struct TestAlternatePngItemView {
11783            focus_handle: FocusHandle,
11784        }
11785
11786        impl Item for TestAlternatePngItemView {
11787            type Event = ();
11788            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11789                "".into()
11790            }
11791        }
11792
11793        impl EventEmitter<()> for TestAlternatePngItemView {}
11794        impl Focusable for TestAlternatePngItemView {
11795            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11796                self.focus_handle.clone()
11797            }
11798        }
11799
11800        impl Render for TestAlternatePngItemView {
11801            fn render(
11802                &mut self,
11803                _window: &mut Window,
11804                _cx: &mut Context<Self>,
11805            ) -> impl IntoElement {
11806                Empty
11807            }
11808        }
11809
11810        impl ProjectItem for TestAlternatePngItemView {
11811            type Item = TestPngItem;
11812
11813            fn for_project_item(
11814                _project: Entity<Project>,
11815                _pane: Option<&Pane>,
11816                _item: Entity<Self::Item>,
11817                _: &mut Window,
11818                cx: &mut Context<Self>,
11819            ) -> Self
11820            where
11821                Self: Sized,
11822            {
11823                Self {
11824                    focus_handle: cx.focus_handle(),
11825                }
11826            }
11827        }
11828
11829        #[gpui::test]
11830        async fn test_register_project_item(cx: &mut TestAppContext) {
11831            init_test(cx);
11832
11833            cx.update(|cx| {
11834                register_project_item::<TestPngItemView>(cx);
11835                register_project_item::<TestIpynbItemView>(cx);
11836            });
11837
11838            let fs = FakeFs::new(cx.executor());
11839            fs.insert_tree(
11840                "/root1",
11841                json!({
11842                    "one.png": "BINARYDATAHERE",
11843                    "two.ipynb": "{ totally a notebook }",
11844                    "three.txt": "editing text, sure why not?"
11845                }),
11846            )
11847            .await;
11848
11849            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11850            let (workspace, cx) =
11851                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11852
11853            let worktree_id = project.update(cx, |project, cx| {
11854                project.worktrees(cx).next().unwrap().read(cx).id()
11855            });
11856
11857            let handle = workspace
11858                .update_in(cx, |workspace, window, cx| {
11859                    let project_path = (worktree_id, rel_path("one.png"));
11860                    workspace.open_path(project_path, None, true, window, cx)
11861                })
11862                .await
11863                .unwrap();
11864
11865            // Now we can check if the handle we got back errored or not
11866            assert_eq!(
11867                handle.to_any_view().entity_type(),
11868                TypeId::of::<TestPngItemView>()
11869            );
11870
11871            let handle = workspace
11872                .update_in(cx, |workspace, window, cx| {
11873                    let project_path = (worktree_id, rel_path("two.ipynb"));
11874                    workspace.open_path(project_path, None, true, window, cx)
11875                })
11876                .await
11877                .unwrap();
11878
11879            assert_eq!(
11880                handle.to_any_view().entity_type(),
11881                TypeId::of::<TestIpynbItemView>()
11882            );
11883
11884            let handle = workspace
11885                .update_in(cx, |workspace, window, cx| {
11886                    let project_path = (worktree_id, rel_path("three.txt"));
11887                    workspace.open_path(project_path, None, true, window, cx)
11888                })
11889                .await;
11890            assert!(handle.is_err());
11891        }
11892
11893        #[gpui::test]
11894        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11895            init_test(cx);
11896
11897            cx.update(|cx| {
11898                register_project_item::<TestPngItemView>(cx);
11899                register_project_item::<TestAlternatePngItemView>(cx);
11900            });
11901
11902            let fs = FakeFs::new(cx.executor());
11903            fs.insert_tree(
11904                "/root1",
11905                json!({
11906                    "one.png": "BINARYDATAHERE",
11907                    "two.ipynb": "{ totally a notebook }",
11908                    "three.txt": "editing text, sure why not?"
11909                }),
11910            )
11911            .await;
11912            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11913            let (workspace, cx) =
11914                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11915            let worktree_id = project.update(cx, |project, cx| {
11916                project.worktrees(cx).next().unwrap().read(cx).id()
11917            });
11918
11919            let handle = workspace
11920                .update_in(cx, |workspace, window, cx| {
11921                    let project_path = (worktree_id, rel_path("one.png"));
11922                    workspace.open_path(project_path, None, true, window, cx)
11923                })
11924                .await
11925                .unwrap();
11926
11927            // This _must_ be the second item registered
11928            assert_eq!(
11929                handle.to_any_view().entity_type(),
11930                TypeId::of::<TestAlternatePngItemView>()
11931            );
11932
11933            let handle = workspace
11934                .update_in(cx, |workspace, window, cx| {
11935                    let project_path = (worktree_id, rel_path("three.txt"));
11936                    workspace.open_path(project_path, None, true, window, cx)
11937                })
11938                .await;
11939            assert!(handle.is_err());
11940        }
11941    }
11942
11943    #[gpui::test]
11944    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11945        init_test(cx);
11946
11947        let fs = FakeFs::new(cx.executor());
11948        let project = Project::test(fs, [], cx).await;
11949        let (workspace, _cx) =
11950            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11951
11952        // Test with status bar shown (default)
11953        workspace.read_with(cx, |workspace, cx| {
11954            let visible = workspace.status_bar_visible(cx);
11955            assert!(visible, "Status bar should be visible by default");
11956        });
11957
11958        // Test with status bar hidden
11959        cx.update_global(|store: &mut SettingsStore, cx| {
11960            store.update_user_settings(cx, |settings| {
11961                settings.status_bar.get_or_insert_default().show = Some(false);
11962            });
11963        });
11964
11965        workspace.read_with(cx, |workspace, cx| {
11966            let visible = workspace.status_bar_visible(cx);
11967            assert!(!visible, "Status bar should be hidden when show is false");
11968        });
11969
11970        // Test with status bar shown explicitly
11971        cx.update_global(|store: &mut SettingsStore, cx| {
11972            store.update_user_settings(cx, |settings| {
11973                settings.status_bar.get_or_insert_default().show = Some(true);
11974            });
11975        });
11976
11977        workspace.read_with(cx, |workspace, cx| {
11978            let visible = workspace.status_bar_visible(cx);
11979            assert!(visible, "Status bar should be visible when show is true");
11980        });
11981    }
11982
11983    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11984        pane.read(cx)
11985            .items()
11986            .flat_map(|item| {
11987                item.project_paths(cx)
11988                    .into_iter()
11989                    .map(|path| path.path.display(PathStyle::local()).into_owned())
11990            })
11991            .collect()
11992    }
11993
11994    pub fn init_test(cx: &mut TestAppContext) {
11995        cx.update(|cx| {
11996            let settings_store = SettingsStore::test(cx);
11997            cx.set_global(settings_store);
11998            theme::init(theme::LoadThemes::JustBase, cx);
11999        });
12000    }
12001
12002    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12003        let item = TestProjectItem::new(id, path, cx);
12004        item.update(cx, |item, _| {
12005            item.is_dirty = true;
12006        });
12007        item
12008    }
12009}