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