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::DisconnectedFromRemote => {
 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            views: active_view.iter().cloned().collect(),
 4949            active_view,
 4950        }
 4951    }
 4952
 4953    fn handle_update_followers(
 4954        &mut self,
 4955        leader_id: PeerId,
 4956        message: proto::UpdateFollowers,
 4957        _window: &mut Window,
 4958        _cx: &mut Context<Self>,
 4959    ) {
 4960        self.leader_updates_tx
 4961            .unbounded_send((leader_id, message))
 4962            .ok();
 4963    }
 4964
 4965    async fn process_leader_update(
 4966        this: &WeakEntity<Self>,
 4967        leader_id: PeerId,
 4968        update: proto::UpdateFollowers,
 4969        cx: &mut AsyncWindowContext,
 4970    ) -> Result<()> {
 4971        match update.variant.context("invalid update")? {
 4972            proto::update_followers::Variant::CreateView(view) => {
 4973                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4974                let should_add_view = this.update(cx, |this, _| {
 4975                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4976                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4977                    } else {
 4978                        anyhow::Ok(false)
 4979                    }
 4980                })??;
 4981
 4982                if should_add_view {
 4983                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4984                }
 4985            }
 4986            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4987                let should_add_view = this.update(cx, |this, _| {
 4988                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4989                        state.active_view_id = update_active_view
 4990                            .view
 4991                            .as_ref()
 4992                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4993
 4994                        if state.active_view_id.is_some_and(|view_id| {
 4995                            !state.items_by_leader_view_id.contains_key(&view_id)
 4996                        }) {
 4997                            anyhow::Ok(true)
 4998                        } else {
 4999                            anyhow::Ok(false)
 5000                        }
 5001                    } else {
 5002                        anyhow::Ok(false)
 5003                    }
 5004                })??;
 5005
 5006                if should_add_view && let Some(view) = update_active_view.view {
 5007                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5008                }
 5009            }
 5010            proto::update_followers::Variant::UpdateView(update_view) => {
 5011                let variant = update_view.variant.context("missing update view variant")?;
 5012                let id = update_view.id.context("missing update view id")?;
 5013                let mut tasks = Vec::new();
 5014                this.update_in(cx, |this, window, cx| {
 5015                    let project = this.project.clone();
 5016                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5017                        let view_id = ViewId::from_proto(id.clone())?;
 5018                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5019                            tasks.push(item.view.apply_update_proto(
 5020                                &project,
 5021                                variant.clone(),
 5022                                window,
 5023                                cx,
 5024                            ));
 5025                        }
 5026                    }
 5027                    anyhow::Ok(())
 5028                })??;
 5029                try_join_all(tasks).await.log_err();
 5030            }
 5031        }
 5032        this.update_in(cx, |this, window, cx| {
 5033            this.leader_updated(leader_id, window, cx)
 5034        })?;
 5035        Ok(())
 5036    }
 5037
 5038    async fn add_view_from_leader(
 5039        this: WeakEntity<Self>,
 5040        leader_id: PeerId,
 5041        view: &proto::View,
 5042        cx: &mut AsyncWindowContext,
 5043    ) -> Result<()> {
 5044        let this = this.upgrade().context("workspace dropped")?;
 5045
 5046        let Some(id) = view.id.clone() else {
 5047            anyhow::bail!("no id for view");
 5048        };
 5049        let id = ViewId::from_proto(id)?;
 5050        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5051
 5052        let pane = this.update(cx, |this, _cx| {
 5053            let state = this
 5054                .follower_states
 5055                .get(&leader_id.into())
 5056                .context("stopped following")?;
 5057            anyhow::Ok(state.pane().clone())
 5058        })??;
 5059        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5060            let client = this.read(cx).client().clone();
 5061            pane.items().find_map(|item| {
 5062                let item = item.to_followable_item_handle(cx)?;
 5063                if item.remote_id(&client, window, cx) == Some(id) {
 5064                    Some(item)
 5065                } else {
 5066                    None
 5067                }
 5068            })
 5069        })?;
 5070        let item = if let Some(existing_item) = existing_item {
 5071            existing_item
 5072        } else {
 5073            let variant = view.variant.clone();
 5074            anyhow::ensure!(variant.is_some(), "missing view variant");
 5075
 5076            let task = cx.update(|window, cx| {
 5077                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5078            })?;
 5079
 5080            let Some(task) = task else {
 5081                anyhow::bail!(
 5082                    "failed to construct view from leader (maybe from a different version of zed?)"
 5083                );
 5084            };
 5085
 5086            let mut new_item = task.await?;
 5087            pane.update_in(cx, |pane, window, cx| {
 5088                let mut item_to_remove = None;
 5089                for (ix, item) in pane.items().enumerate() {
 5090                    if let Some(item) = item.to_followable_item_handle(cx) {
 5091                        match new_item.dedup(item.as_ref(), window, cx) {
 5092                            Some(item::Dedup::KeepExisting) => {
 5093                                new_item =
 5094                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5095                                break;
 5096                            }
 5097                            Some(item::Dedup::ReplaceExisting) => {
 5098                                item_to_remove = Some((ix, item.item_id()));
 5099                                break;
 5100                            }
 5101                            None => {}
 5102                        }
 5103                    }
 5104                }
 5105
 5106                if let Some((ix, id)) = item_to_remove {
 5107                    pane.remove_item(id, false, false, window, cx);
 5108                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5109                }
 5110            })?;
 5111
 5112            new_item
 5113        };
 5114
 5115        this.update_in(cx, |this, window, cx| {
 5116            let state = this.follower_states.get_mut(&leader_id.into())?;
 5117            item.set_leader_id(Some(leader_id.into()), window, cx);
 5118            state.items_by_leader_view_id.insert(
 5119                id,
 5120                FollowerView {
 5121                    view: item,
 5122                    location: panel_id,
 5123                },
 5124            );
 5125
 5126            Some(())
 5127        })?;
 5128
 5129        Ok(())
 5130    }
 5131
 5132    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5133        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5134            return;
 5135        };
 5136
 5137        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5138            let buffer_entity_id = agent_location.buffer.entity_id();
 5139            let view_id = ViewId {
 5140                creator: CollaboratorId::Agent,
 5141                id: buffer_entity_id.as_u64(),
 5142            };
 5143            follower_state.active_view_id = Some(view_id);
 5144
 5145            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5146                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5147                hash_map::Entry::Vacant(entry) => {
 5148                    let existing_view =
 5149                        follower_state
 5150                            .center_pane
 5151                            .read(cx)
 5152                            .items()
 5153                            .find_map(|item| {
 5154                                let item = item.to_followable_item_handle(cx)?;
 5155                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5156                                    && item.project_item_model_ids(cx).as_slice()
 5157                                        == [buffer_entity_id]
 5158                                {
 5159                                    Some(item)
 5160                                } else {
 5161                                    None
 5162                                }
 5163                            });
 5164                    let view = existing_view.or_else(|| {
 5165                        agent_location.buffer.upgrade().and_then(|buffer| {
 5166                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5167                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5168                            })?
 5169                            .to_followable_item_handle(cx)
 5170                        })
 5171                    });
 5172
 5173                    view.map(|view| {
 5174                        entry.insert(FollowerView {
 5175                            view,
 5176                            location: None,
 5177                        })
 5178                    })
 5179                }
 5180            };
 5181
 5182            if let Some(item) = item {
 5183                item.view
 5184                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5185                item.view
 5186                    .update_agent_location(agent_location.position, window, cx);
 5187            }
 5188        } else {
 5189            follower_state.active_view_id = None;
 5190        }
 5191
 5192        self.leader_updated(CollaboratorId::Agent, window, cx);
 5193    }
 5194
 5195    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5196        let mut is_project_item = true;
 5197        let mut update = proto::UpdateActiveView::default();
 5198        if window.is_window_active() {
 5199            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5200
 5201            if let Some(item) = active_item
 5202                && item.item_focus_handle(cx).contains_focused(window, cx)
 5203            {
 5204                let leader_id = self
 5205                    .pane_for(&*item)
 5206                    .and_then(|pane| self.leader_for_pane(&pane));
 5207                let leader_peer_id = match leader_id {
 5208                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5209                    Some(CollaboratorId::Agent) | None => None,
 5210                };
 5211
 5212                if let Some(item) = item.to_followable_item_handle(cx) {
 5213                    let id = item
 5214                        .remote_id(&self.app_state.client, window, cx)
 5215                        .map(|id| id.to_proto());
 5216
 5217                    if let Some(id) = id
 5218                        && let Some(variant) = item.to_state_proto(window, cx)
 5219                    {
 5220                        let view = Some(proto::View {
 5221                            id,
 5222                            leader_id: leader_peer_id,
 5223                            variant: Some(variant),
 5224                            panel_id: panel_id.map(|id| id as i32),
 5225                        });
 5226
 5227                        is_project_item = item.is_project_item(window, cx);
 5228                        update = proto::UpdateActiveView { view };
 5229                    };
 5230                }
 5231            }
 5232        }
 5233
 5234        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5235        if active_view_id != self.last_active_view_id.as_ref() {
 5236            self.last_active_view_id = active_view_id.cloned();
 5237            self.update_followers(
 5238                is_project_item,
 5239                proto::update_followers::Variant::UpdateActiveView(update),
 5240                window,
 5241                cx,
 5242            );
 5243        }
 5244    }
 5245
 5246    fn active_item_for_followers(
 5247        &self,
 5248        window: &mut Window,
 5249        cx: &mut App,
 5250    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5251        let mut active_item = None;
 5252        let mut panel_id = None;
 5253        for dock in self.all_docks() {
 5254            if dock.focus_handle(cx).contains_focused(window, cx)
 5255                && let Some(panel) = dock.read(cx).active_panel()
 5256                && let Some(pane) = panel.pane(cx)
 5257                && let Some(item) = pane.read(cx).active_item()
 5258            {
 5259                active_item = Some(item);
 5260                panel_id = panel.remote_id();
 5261                break;
 5262            }
 5263        }
 5264
 5265        if active_item.is_none() {
 5266            active_item = self.active_pane().read(cx).active_item();
 5267        }
 5268        (active_item, panel_id)
 5269    }
 5270
 5271    fn update_followers(
 5272        &self,
 5273        project_only: bool,
 5274        update: proto::update_followers::Variant,
 5275        _: &mut Window,
 5276        cx: &mut App,
 5277    ) -> Option<()> {
 5278        // If this update only applies to for followers in the current project,
 5279        // then skip it unless this project is shared. If it applies to all
 5280        // followers, regardless of project, then set `project_id` to none,
 5281        // indicating that it goes to all followers.
 5282        let project_id = if project_only {
 5283            Some(self.project.read(cx).remote_id()?)
 5284        } else {
 5285            None
 5286        };
 5287        self.app_state().workspace_store.update(cx, |store, cx| {
 5288            store.update_followers(project_id, update, cx)
 5289        })
 5290    }
 5291
 5292    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5293        self.follower_states.iter().find_map(|(leader_id, state)| {
 5294            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5295                Some(*leader_id)
 5296            } else {
 5297                None
 5298            }
 5299        })
 5300    }
 5301
 5302    fn leader_updated(
 5303        &mut self,
 5304        leader_id: impl Into<CollaboratorId>,
 5305        window: &mut Window,
 5306        cx: &mut Context<Self>,
 5307    ) -> Option<Box<dyn ItemHandle>> {
 5308        cx.notify();
 5309
 5310        let leader_id = leader_id.into();
 5311        let (panel_id, item) = match leader_id {
 5312            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5313            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5314        };
 5315
 5316        let state = self.follower_states.get(&leader_id)?;
 5317        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5318        let pane;
 5319        if let Some(panel_id) = panel_id {
 5320            pane = self
 5321                .activate_panel_for_proto_id(panel_id, window, cx)?
 5322                .pane(cx)?;
 5323            let state = self.follower_states.get_mut(&leader_id)?;
 5324            state.dock_pane = Some(pane.clone());
 5325        } else {
 5326            pane = state.center_pane.clone();
 5327            let state = self.follower_states.get_mut(&leader_id)?;
 5328            if let Some(dock_pane) = state.dock_pane.take() {
 5329                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5330            }
 5331        }
 5332
 5333        pane.update(cx, |pane, cx| {
 5334            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5335            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5336                pane.activate_item(index, false, false, window, cx);
 5337            } else {
 5338                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5339            }
 5340
 5341            if focus_active_item {
 5342                pane.focus_active_item(window, cx)
 5343            }
 5344        });
 5345
 5346        Some(item)
 5347    }
 5348
 5349    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5350        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5351        let active_view_id = state.active_view_id?;
 5352        Some(
 5353            state
 5354                .items_by_leader_view_id
 5355                .get(&active_view_id)?
 5356                .view
 5357                .boxed_clone(),
 5358        )
 5359    }
 5360
 5361    fn active_item_for_peer(
 5362        &self,
 5363        peer_id: PeerId,
 5364        window: &mut Window,
 5365        cx: &mut Context<Self>,
 5366    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5367        let call = self.active_call()?;
 5368        let room = call.read(cx).room()?.read(cx);
 5369        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5370        let leader_in_this_app;
 5371        let leader_in_this_project;
 5372        match participant.location {
 5373            call::ParticipantLocation::SharedProject { project_id } => {
 5374                leader_in_this_app = true;
 5375                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5376            }
 5377            call::ParticipantLocation::UnsharedProject => {
 5378                leader_in_this_app = true;
 5379                leader_in_this_project = false;
 5380            }
 5381            call::ParticipantLocation::External => {
 5382                leader_in_this_app = false;
 5383                leader_in_this_project = false;
 5384            }
 5385        };
 5386        let state = self.follower_states.get(&peer_id.into())?;
 5387        let mut item_to_activate = None;
 5388        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5389            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5390                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5391            {
 5392                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5393            }
 5394        } else if let Some(shared_screen) =
 5395            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5396        {
 5397            item_to_activate = Some((None, Box::new(shared_screen)));
 5398        }
 5399        item_to_activate
 5400    }
 5401
 5402    fn shared_screen_for_peer(
 5403        &self,
 5404        peer_id: PeerId,
 5405        pane: &Entity<Pane>,
 5406        window: &mut Window,
 5407        cx: &mut App,
 5408    ) -> Option<Entity<SharedScreen>> {
 5409        let call = self.active_call()?;
 5410        let room = call.read(cx).room()?.clone();
 5411        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5412        let track = participant.video_tracks.values().next()?.clone();
 5413        let user = participant.user.clone();
 5414
 5415        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5416            if item.read(cx).peer_id == peer_id {
 5417                return Some(item);
 5418            }
 5419        }
 5420
 5421        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5422    }
 5423
 5424    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5425        if window.is_window_active() {
 5426            self.update_active_view_for_followers(window, cx);
 5427
 5428            if let Some(database_id) = self.database_id {
 5429                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5430                    .detach();
 5431            }
 5432        } else {
 5433            for pane in &self.panes {
 5434                pane.update(cx, |pane, cx| {
 5435                    if let Some(item) = pane.active_item() {
 5436                        item.workspace_deactivated(window, cx);
 5437                    }
 5438                    for item in pane.items() {
 5439                        if matches!(
 5440                            item.workspace_settings(cx).autosave,
 5441                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5442                        ) {
 5443                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5444                                .detach_and_log_err(cx);
 5445                        }
 5446                    }
 5447                });
 5448            }
 5449        }
 5450    }
 5451
 5452    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5453        self.active_call.as_ref().map(|(call, _)| call)
 5454    }
 5455
 5456    fn on_active_call_event(
 5457        &mut self,
 5458        _: &Entity<ActiveCall>,
 5459        event: &call::room::Event,
 5460        window: &mut Window,
 5461        cx: &mut Context<Self>,
 5462    ) {
 5463        match event {
 5464            call::room::Event::ParticipantLocationChanged { participant_id }
 5465            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5466                self.leader_updated(participant_id, window, cx);
 5467            }
 5468            _ => {}
 5469        }
 5470    }
 5471
 5472    pub fn database_id(&self) -> Option<WorkspaceId> {
 5473        self.database_id
 5474    }
 5475
 5476    pub fn session_id(&self) -> Option<String> {
 5477        self.session_id.clone()
 5478    }
 5479
 5480    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5481        let project = self.project().read(cx);
 5482        project
 5483            .visible_worktrees(cx)
 5484            .map(|worktree| worktree.read(cx).abs_path())
 5485            .collect::<Vec<_>>()
 5486    }
 5487
 5488    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5489        match member {
 5490            Member::Axis(PaneAxis { members, .. }) => {
 5491                for child in members.iter() {
 5492                    self.remove_panes(child.clone(), window, cx)
 5493                }
 5494            }
 5495            Member::Pane(pane) => {
 5496                self.force_remove_pane(&pane, &None, window, cx);
 5497            }
 5498        }
 5499    }
 5500
 5501    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5502        self.session_id.take();
 5503        self.serialize_workspace_internal(window, cx)
 5504    }
 5505
 5506    fn force_remove_pane(
 5507        &mut self,
 5508        pane: &Entity<Pane>,
 5509        focus_on: &Option<Entity<Pane>>,
 5510        window: &mut Window,
 5511        cx: &mut Context<Workspace>,
 5512    ) {
 5513        self.panes.retain(|p| p != pane);
 5514        if let Some(focus_on) = focus_on {
 5515            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5516        } else if self.active_pane() == pane {
 5517            self.panes
 5518                .last()
 5519                .unwrap()
 5520                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5521        }
 5522        if self.last_active_center_pane == Some(pane.downgrade()) {
 5523            self.last_active_center_pane = None;
 5524        }
 5525        cx.notify();
 5526    }
 5527
 5528    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5529        if self._schedule_serialize_workspace.is_none() {
 5530            self._schedule_serialize_workspace =
 5531                Some(cx.spawn_in(window, async move |this, cx| {
 5532                    cx.background_executor()
 5533                        .timer(SERIALIZATION_THROTTLE_TIME)
 5534                        .await;
 5535                    this.update_in(cx, |this, window, cx| {
 5536                        this.serialize_workspace_internal(window, cx).detach();
 5537                        this._schedule_serialize_workspace.take();
 5538                    })
 5539                    .log_err();
 5540                }));
 5541        }
 5542    }
 5543
 5544    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5545        let Some(database_id) = self.database_id() else {
 5546            return Task::ready(());
 5547        };
 5548
 5549        fn serialize_pane_handle(
 5550            pane_handle: &Entity<Pane>,
 5551            window: &mut Window,
 5552            cx: &mut App,
 5553        ) -> SerializedPane {
 5554            let (items, active, pinned_count) = {
 5555                let pane = pane_handle.read(cx);
 5556                let active_item_id = pane.active_item().map(|item| item.item_id());
 5557                (
 5558                    pane.items()
 5559                        .filter_map(|handle| {
 5560                            let handle = handle.to_serializable_item_handle(cx)?;
 5561
 5562                            Some(SerializedItem {
 5563                                kind: Arc::from(handle.serialized_item_kind()),
 5564                                item_id: handle.item_id().as_u64(),
 5565                                active: Some(handle.item_id()) == active_item_id,
 5566                                preview: pane.is_active_preview_item(handle.item_id()),
 5567                            })
 5568                        })
 5569                        .collect::<Vec<_>>(),
 5570                    pane.has_focus(window, cx),
 5571                    pane.pinned_count(),
 5572                )
 5573            };
 5574
 5575            SerializedPane::new(items, active, pinned_count)
 5576        }
 5577
 5578        fn build_serialized_pane_group(
 5579            pane_group: &Member,
 5580            window: &mut Window,
 5581            cx: &mut App,
 5582        ) -> SerializedPaneGroup {
 5583            match pane_group {
 5584                Member::Axis(PaneAxis {
 5585                    axis,
 5586                    members,
 5587                    flexes,
 5588                    bounding_boxes: _,
 5589                }) => SerializedPaneGroup::Group {
 5590                    axis: SerializedAxis(*axis),
 5591                    children: members
 5592                        .iter()
 5593                        .map(|member| build_serialized_pane_group(member, window, cx))
 5594                        .collect::<Vec<_>>(),
 5595                    flexes: Some(flexes.lock().clone()),
 5596                },
 5597                Member::Pane(pane_handle) => {
 5598                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5599                }
 5600            }
 5601        }
 5602
 5603        fn build_serialized_docks(
 5604            this: &Workspace,
 5605            window: &mut Window,
 5606            cx: &mut App,
 5607        ) -> DockStructure {
 5608            let left_dock = this.left_dock.read(cx);
 5609            let left_visible = left_dock.is_open();
 5610            let left_active_panel = left_dock
 5611                .active_panel()
 5612                .map(|panel| panel.persistent_name().to_string());
 5613            let left_dock_zoom = left_dock
 5614                .active_panel()
 5615                .map(|panel| panel.is_zoomed(window, cx))
 5616                .unwrap_or(false);
 5617
 5618            let right_dock = this.right_dock.read(cx);
 5619            let right_visible = right_dock.is_open();
 5620            let right_active_panel = right_dock
 5621                .active_panel()
 5622                .map(|panel| panel.persistent_name().to_string());
 5623            let right_dock_zoom = right_dock
 5624                .active_panel()
 5625                .map(|panel| panel.is_zoomed(window, cx))
 5626                .unwrap_or(false);
 5627
 5628            let bottom_dock = this.bottom_dock.read(cx);
 5629            let bottom_visible = bottom_dock.is_open();
 5630            let bottom_active_panel = bottom_dock
 5631                .active_panel()
 5632                .map(|panel| panel.persistent_name().to_string());
 5633            let bottom_dock_zoom = bottom_dock
 5634                .active_panel()
 5635                .map(|panel| panel.is_zoomed(window, cx))
 5636                .unwrap_or(false);
 5637
 5638            DockStructure {
 5639                left: DockData {
 5640                    visible: left_visible,
 5641                    active_panel: left_active_panel,
 5642                    zoom: left_dock_zoom,
 5643                },
 5644                right: DockData {
 5645                    visible: right_visible,
 5646                    active_panel: right_active_panel,
 5647                    zoom: right_dock_zoom,
 5648                },
 5649                bottom: DockData {
 5650                    visible: bottom_visible,
 5651                    active_panel: bottom_active_panel,
 5652                    zoom: bottom_dock_zoom,
 5653                },
 5654            }
 5655        }
 5656
 5657        match self.serialize_workspace_location(cx) {
 5658            WorkspaceLocation::Location(location, paths) => {
 5659                let breakpoints = self.project.update(cx, |project, cx| {
 5660                    project
 5661                        .breakpoint_store()
 5662                        .read(cx)
 5663                        .all_source_breakpoints(cx)
 5664                });
 5665                let user_toolchains = self
 5666                    .project
 5667                    .read(cx)
 5668                    .user_toolchains(cx)
 5669                    .unwrap_or_default();
 5670
 5671                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5672                let docks = build_serialized_docks(self, window, cx);
 5673                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5674
 5675                let serialized_workspace = SerializedWorkspace {
 5676                    id: database_id,
 5677                    location,
 5678                    paths,
 5679                    center_group,
 5680                    window_bounds,
 5681                    display: Default::default(),
 5682                    docks,
 5683                    centered_layout: self.centered_layout,
 5684                    session_id: self.session_id.clone(),
 5685                    breakpoints,
 5686                    window_id: Some(window.window_handle().window_id().as_u64()),
 5687                    user_toolchains,
 5688                };
 5689
 5690                window.spawn(cx, async move |_| {
 5691                    persistence::DB.save_workspace(serialized_workspace).await;
 5692                })
 5693            }
 5694            WorkspaceLocation::DetachFromSession => {
 5695                let window_bounds = SerializedWindowBounds(window.window_bounds());
 5696                let display = window.display(cx).and_then(|d| d.uuid().ok());
 5697                window.spawn(cx, async move |_| {
 5698                    persistence::DB
 5699                        .set_window_open_status(
 5700                            database_id,
 5701                            window_bounds,
 5702                            display.unwrap_or_default(),
 5703                        )
 5704                        .await
 5705                        .log_err();
 5706                    persistence::DB
 5707                        .set_session_id(database_id, None)
 5708                        .await
 5709                        .log_err();
 5710                })
 5711            }
 5712            WorkspaceLocation::None => Task::ready(()),
 5713        }
 5714    }
 5715
 5716    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5717        let paths = PathList::new(&self.root_paths(cx));
 5718        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5719            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 5720        } else if self.project.read(cx).is_local() {
 5721            if !paths.is_empty() {
 5722                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5723            } else {
 5724                WorkspaceLocation::DetachFromSession
 5725            }
 5726        } else {
 5727            WorkspaceLocation::None
 5728        }
 5729    }
 5730
 5731    fn update_history(&self, cx: &mut App) {
 5732        let Some(id) = self.database_id() else {
 5733            return;
 5734        };
 5735        if !self.project.read(cx).is_local() {
 5736            return;
 5737        }
 5738        if let Some(manager) = HistoryManager::global(cx) {
 5739            let paths = PathList::new(&self.root_paths(cx));
 5740            manager.update(cx, |this, cx| {
 5741                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5742            });
 5743        }
 5744    }
 5745
 5746    async fn serialize_items(
 5747        this: &WeakEntity<Self>,
 5748        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5749        cx: &mut AsyncWindowContext,
 5750    ) -> Result<()> {
 5751        const CHUNK_SIZE: usize = 200;
 5752
 5753        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5754
 5755        while let Some(items_received) = serializable_items.next().await {
 5756            let unique_items =
 5757                items_received
 5758                    .into_iter()
 5759                    .fold(HashMap::default(), |mut acc, item| {
 5760                        acc.entry(item.item_id()).or_insert(item);
 5761                        acc
 5762                    });
 5763
 5764            // We use into_iter() here so that the references to the items are moved into
 5765            // the tasks and not kept alive while we're sleeping.
 5766            for (_, item) in unique_items.into_iter() {
 5767                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5768                    item.serialize(workspace, false, window, cx)
 5769                }) {
 5770                    cx.background_spawn(async move { task.await.log_err() })
 5771                        .detach();
 5772                }
 5773            }
 5774
 5775            cx.background_executor()
 5776                .timer(SERIALIZATION_THROTTLE_TIME)
 5777                .await;
 5778        }
 5779
 5780        Ok(())
 5781    }
 5782
 5783    pub(crate) fn enqueue_item_serialization(
 5784        &mut self,
 5785        item: Box<dyn SerializableItemHandle>,
 5786    ) -> Result<()> {
 5787        self.serializable_items_tx
 5788            .unbounded_send(item)
 5789            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5790    }
 5791
 5792    pub(crate) fn load_workspace(
 5793        serialized_workspace: SerializedWorkspace,
 5794        paths_to_open: Vec<Option<ProjectPath>>,
 5795        window: &mut Window,
 5796        cx: &mut Context<Workspace>,
 5797    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5798        cx.spawn_in(window, async move |workspace, cx| {
 5799            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5800
 5801            let mut center_group = None;
 5802            let mut center_items = None;
 5803
 5804            // Traverse the splits tree and add to things
 5805            if let Some((group, active_pane, items)) = serialized_workspace
 5806                .center_group
 5807                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5808                .await
 5809            {
 5810                center_items = Some(items);
 5811                center_group = Some((group, active_pane))
 5812            }
 5813
 5814            let mut items_by_project_path = HashMap::default();
 5815            let mut item_ids_by_kind = HashMap::default();
 5816            let mut all_deserialized_items = Vec::default();
 5817            cx.update(|_, cx| {
 5818                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5819                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5820                        item_ids_by_kind
 5821                            .entry(serializable_item_handle.serialized_item_kind())
 5822                            .or_insert(Vec::new())
 5823                            .push(item.item_id().as_u64() as ItemId);
 5824                    }
 5825
 5826                    if let Some(project_path) = item.project_path(cx) {
 5827                        items_by_project_path.insert(project_path, item.clone());
 5828                    }
 5829                    all_deserialized_items.push(item);
 5830                }
 5831            })?;
 5832
 5833            let opened_items = paths_to_open
 5834                .into_iter()
 5835                .map(|path_to_open| {
 5836                    path_to_open
 5837                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5838                })
 5839                .collect::<Vec<_>>();
 5840
 5841            // Remove old panes from workspace panes list
 5842            workspace.update_in(cx, |workspace, window, cx| {
 5843                if let Some((center_group, active_pane)) = center_group {
 5844                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5845
 5846                    // Swap workspace center group
 5847                    workspace.center = PaneGroup::with_root(center_group);
 5848                    workspace.center.set_is_center(true);
 5849                    workspace.center.mark_positions(cx);
 5850
 5851                    if let Some(active_pane) = active_pane {
 5852                        workspace.set_active_pane(&active_pane, window, cx);
 5853                        cx.focus_self(window);
 5854                    } else {
 5855                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5856                    }
 5857                }
 5858
 5859                let docks = serialized_workspace.docks;
 5860
 5861                for (dock, serialized_dock) in [
 5862                    (&mut workspace.right_dock, docks.right),
 5863                    (&mut workspace.left_dock, docks.left),
 5864                    (&mut workspace.bottom_dock, docks.bottom),
 5865                ]
 5866                .iter_mut()
 5867                {
 5868                    dock.update(cx, |dock, cx| {
 5869                        dock.serialized_dock = Some(serialized_dock.clone());
 5870                        dock.restore_state(window, cx);
 5871                    });
 5872                }
 5873
 5874                cx.notify();
 5875            })?;
 5876
 5877            let _ = project
 5878                .update(cx, |project, cx| {
 5879                    project
 5880                        .breakpoint_store()
 5881                        .update(cx, |breakpoint_store, cx| {
 5882                            breakpoint_store
 5883                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5884                        })
 5885                })?
 5886                .await;
 5887
 5888            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5889            // after loading the items, we might have different items and in order to avoid
 5890            // the database filling up, we delete items that haven't been loaded now.
 5891            //
 5892            // The items that have been loaded, have been saved after they've been added to the workspace.
 5893            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5894                item_ids_by_kind
 5895                    .into_iter()
 5896                    .map(|(item_kind, loaded_items)| {
 5897                        SerializableItemRegistry::cleanup(
 5898                            item_kind,
 5899                            serialized_workspace.id,
 5900                            loaded_items,
 5901                            window,
 5902                            cx,
 5903                        )
 5904                        .log_err()
 5905                    })
 5906                    .collect::<Vec<_>>()
 5907            })?;
 5908
 5909            futures::future::join_all(clean_up_tasks).await;
 5910
 5911            workspace
 5912                .update_in(cx, |workspace, window, cx| {
 5913                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5914                    workspace.serialize_workspace_internal(window, cx).detach();
 5915
 5916                    // Ensure that we mark the window as edited if we did load dirty items
 5917                    workspace.update_window_edited(window, cx);
 5918                })
 5919                .ok();
 5920
 5921            Ok(opened_items)
 5922        })
 5923    }
 5924
 5925    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5926        self.add_workspace_actions_listeners(div, window, cx)
 5927            .on_action(cx.listener(
 5928                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 5929                    for action in &action_sequence.0 {
 5930                        window.dispatch_action(action.boxed_clone(), cx);
 5931                    }
 5932                },
 5933            ))
 5934            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5935            .on_action(cx.listener(Self::close_all_items_and_panes))
 5936            .on_action(cx.listener(Self::save_all))
 5937            .on_action(cx.listener(Self::send_keystrokes))
 5938            .on_action(cx.listener(Self::add_folder_to_project))
 5939            .on_action(cx.listener(Self::follow_next_collaborator))
 5940            .on_action(cx.listener(Self::close_window))
 5941            .on_action(cx.listener(Self::activate_pane_at_index))
 5942            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5943            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5944            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 5945            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5946                let pane = workspace.active_pane().clone();
 5947                workspace.unfollow_in_pane(&pane, window, cx);
 5948            }))
 5949            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5950                workspace
 5951                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5952                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5953            }))
 5954            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5955                workspace
 5956                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5957                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5958            }))
 5959            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5960                workspace
 5961                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5962                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5963            }))
 5964            .on_action(
 5965                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5966                    workspace.activate_previous_pane(window, cx)
 5967                }),
 5968            )
 5969            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5970                workspace.activate_next_pane(window, cx)
 5971            }))
 5972            .on_action(
 5973                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5974                    workspace.activate_next_window(cx)
 5975                }),
 5976            )
 5977            .on_action(
 5978                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5979                    workspace.activate_previous_window(cx)
 5980                }),
 5981            )
 5982            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5983                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5984            }))
 5985            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5986                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5987            }))
 5988            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5989                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5990            }))
 5991            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 5992                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 5993            }))
 5994            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5995                workspace.activate_next_pane(window, cx)
 5996            }))
 5997            .on_action(cx.listener(
 5998                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 5999                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6000                },
 6001            ))
 6002            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6003                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6004            }))
 6005            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6006                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6007            }))
 6008            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6009                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6010            }))
 6011            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6012                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6013            }))
 6014            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6015                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6016                    SplitDirection::Down,
 6017                    SplitDirection::Up,
 6018                    SplitDirection::Right,
 6019                    SplitDirection::Left,
 6020                ];
 6021                for dir in DIRECTION_PRIORITY {
 6022                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6023                        workspace.swap_pane_in_direction(dir, cx);
 6024                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6025                        break;
 6026                    }
 6027                }
 6028            }))
 6029            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6030                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6031            }))
 6032            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6033                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6034            }))
 6035            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6036                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6037            }))
 6038            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6039                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6040            }))
 6041            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6042                this.toggle_dock(DockPosition::Left, window, cx);
 6043            }))
 6044            .on_action(cx.listener(
 6045                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6046                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6047                },
 6048            ))
 6049            .on_action(cx.listener(
 6050                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6051                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6052                },
 6053            ))
 6054            .on_action(cx.listener(
 6055                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6056                    if !workspace.close_active_dock(window, cx) {
 6057                        cx.propagate();
 6058                    }
 6059                },
 6060            ))
 6061            .on_action(
 6062                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6063                    workspace.close_all_docks(window, cx);
 6064                }),
 6065            )
 6066            .on_action(cx.listener(Self::toggle_all_docks))
 6067            .on_action(cx.listener(
 6068                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6069                    workspace.clear_all_notifications(cx);
 6070                },
 6071            ))
 6072            .on_action(cx.listener(
 6073                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6074                    workspace.clear_navigation_history(window, cx);
 6075                },
 6076            ))
 6077            .on_action(cx.listener(
 6078                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6079                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6080                        workspace.suppress_notification(&notification_id, cx);
 6081                    }
 6082                },
 6083            ))
 6084            .on_action(cx.listener(
 6085                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6086                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6087                },
 6088            ))
 6089            .on_action(
 6090                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6091                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6092                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6093                            trusted_worktrees.clear_trusted_paths()
 6094                        });
 6095                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6096                        cx.spawn(async move |_, cx| {
 6097                            if clear_task.await.log_err().is_some() {
 6098                                cx.update(|cx| reload(cx)).ok();
 6099                            }
 6100                        })
 6101                        .detach();
 6102                    }
 6103                }),
 6104            )
 6105            .on_action(cx.listener(
 6106                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6107                    workspace.reopen_closed_item(window, cx).detach();
 6108                },
 6109            ))
 6110            .on_action(cx.listener(
 6111                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6112                    for dock in workspace.all_docks() {
 6113                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6114                            let Some(panel) = dock.read(cx).active_panel() else {
 6115                                return;
 6116                            };
 6117
 6118                            // Set to `None`, then the size will fall back to the default.
 6119                            panel.clone().set_size(None, window, cx);
 6120
 6121                            return;
 6122                        }
 6123                    }
 6124                },
 6125            ))
 6126            .on_action(cx.listener(
 6127                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6128                    for dock in workspace.all_docks() {
 6129                        if let Some(panel) = dock.read(cx).visible_panel() {
 6130                            // Set to `None`, then the size will fall back to the default.
 6131                            panel.clone().set_size(None, window, cx);
 6132                        }
 6133                    }
 6134                },
 6135            ))
 6136            .on_action(cx.listener(
 6137                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6138                    adjust_active_dock_size_by_px(
 6139                        px_with_ui_font_fallback(act.px, cx),
 6140                        workspace,
 6141                        window,
 6142                        cx,
 6143                    );
 6144                },
 6145            ))
 6146            .on_action(cx.listener(
 6147                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6148                    adjust_active_dock_size_by_px(
 6149                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6150                        workspace,
 6151                        window,
 6152                        cx,
 6153                    );
 6154                },
 6155            ))
 6156            .on_action(cx.listener(
 6157                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6158                    adjust_open_docks_size_by_px(
 6159                        px_with_ui_font_fallback(act.px, cx),
 6160                        workspace,
 6161                        window,
 6162                        cx,
 6163                    );
 6164                },
 6165            ))
 6166            .on_action(cx.listener(
 6167                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6168                    adjust_open_docks_size_by_px(
 6169                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6170                        workspace,
 6171                        window,
 6172                        cx,
 6173                    );
 6174                },
 6175            ))
 6176            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6177            .on_action(cx.listener(
 6178                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6179                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6180                        let dock = active_dock.read(cx);
 6181                        if let Some(active_panel) = dock.active_panel() {
 6182                            if active_panel.pane(cx).is_none() {
 6183                                let mut recent_pane: Option<Entity<Pane>> = None;
 6184                                let mut recent_timestamp = 0;
 6185                                for pane_handle in workspace.panes() {
 6186                                    let pane = pane_handle.read(cx);
 6187                                    for entry in pane.activation_history() {
 6188                                        if entry.timestamp > recent_timestamp {
 6189                                            recent_timestamp = entry.timestamp;
 6190                                            recent_pane = Some(pane_handle.clone());
 6191                                        }
 6192                                    }
 6193                                }
 6194
 6195                                if let Some(pane) = recent_pane {
 6196                                    pane.update(cx, |pane, cx| {
 6197                                        let current_index = pane.active_item_index();
 6198                                        let items_len = pane.items_len();
 6199                                        if items_len > 0 {
 6200                                            let next_index = if current_index + 1 < items_len {
 6201                                                current_index + 1
 6202                                            } else {
 6203                                                0
 6204                                            };
 6205                                            pane.activate_item(
 6206                                                next_index, false, false, window, cx,
 6207                                            );
 6208                                        }
 6209                                    });
 6210                                    return;
 6211                                }
 6212                            }
 6213                        }
 6214                    }
 6215                    cx.propagate();
 6216                },
 6217            ))
 6218            .on_action(cx.listener(
 6219                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6220                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6221                        let dock = active_dock.read(cx);
 6222                        if let Some(active_panel) = dock.active_panel() {
 6223                            if active_panel.pane(cx).is_none() {
 6224                                let mut recent_pane: Option<Entity<Pane>> = None;
 6225                                let mut recent_timestamp = 0;
 6226                                for pane_handle in workspace.panes() {
 6227                                    let pane = pane_handle.read(cx);
 6228                                    for entry in pane.activation_history() {
 6229                                        if entry.timestamp > recent_timestamp {
 6230                                            recent_timestamp = entry.timestamp;
 6231                                            recent_pane = Some(pane_handle.clone());
 6232                                        }
 6233                                    }
 6234                                }
 6235
 6236                                if let Some(pane) = recent_pane {
 6237                                    pane.update(cx, |pane, cx| {
 6238                                        let current_index = pane.active_item_index();
 6239                                        let items_len = pane.items_len();
 6240                                        if items_len > 0 {
 6241                                            let prev_index = if current_index > 0 {
 6242                                                current_index - 1
 6243                                            } else {
 6244                                                items_len.saturating_sub(1)
 6245                                            };
 6246                                            pane.activate_item(
 6247                                                prev_index, false, false, window, cx,
 6248                                            );
 6249                                        }
 6250                                    });
 6251                                    return;
 6252                                }
 6253                            }
 6254                        }
 6255                    }
 6256                    cx.propagate();
 6257                },
 6258            ))
 6259            .on_action(
 6260                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6261                    let pane = workspace.active_pane().clone();
 6262                    if let Some(item) = pane.read(cx).active_item() {
 6263                        item.toggle_read_only(window, cx);
 6264                    }
 6265                }),
 6266            )
 6267            .on_action(cx.listener(Workspace::cancel))
 6268    }
 6269
 6270    #[cfg(any(test, feature = "test-support"))]
 6271    pub fn set_random_database_id(&mut self) {
 6272        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6273    }
 6274
 6275    #[cfg(any(test, feature = "test-support"))]
 6276    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 6277        use node_runtime::NodeRuntime;
 6278        use session::Session;
 6279
 6280        let client = project.read(cx).client();
 6281        let user_store = project.read(cx).user_store();
 6282        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6283        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6284        window.activate_window();
 6285        let app_state = Arc::new(AppState {
 6286            languages: project.read(cx).languages().clone(),
 6287            workspace_store,
 6288            client,
 6289            user_store,
 6290            fs: project.read(cx).fs().clone(),
 6291            build_window_options: |_, _| Default::default(),
 6292            node_runtime: NodeRuntime::unavailable(),
 6293            session,
 6294        });
 6295        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6296        workspace
 6297            .active_pane
 6298            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6299        workspace
 6300    }
 6301
 6302    pub fn register_action<A: Action>(
 6303        &mut self,
 6304        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6305    ) -> &mut Self {
 6306        let callback = Arc::new(callback);
 6307
 6308        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6309            let callback = callback.clone();
 6310            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6311                (callback)(workspace, event, window, cx)
 6312            }))
 6313        }));
 6314        self
 6315    }
 6316    pub fn register_action_renderer(
 6317        &mut self,
 6318        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6319    ) -> &mut Self {
 6320        self.workspace_actions.push(Box::new(callback));
 6321        self
 6322    }
 6323
 6324    fn add_workspace_actions_listeners(
 6325        &self,
 6326        mut div: Div,
 6327        window: &mut Window,
 6328        cx: &mut Context<Self>,
 6329    ) -> Div {
 6330        for action in self.workspace_actions.iter() {
 6331            div = (action)(div, self, window, cx)
 6332        }
 6333        div
 6334    }
 6335
 6336    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6337        self.modal_layer.read(cx).has_active_modal()
 6338    }
 6339
 6340    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6341        self.modal_layer.read(cx).active_modal()
 6342    }
 6343
 6344    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6345    where
 6346        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6347    {
 6348        self.modal_layer.update(cx, |modal_layer, cx| {
 6349            modal_layer.toggle_modal(window, cx, build)
 6350        })
 6351    }
 6352
 6353    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6354        self.modal_layer
 6355            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6356    }
 6357
 6358    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6359        self.toast_layer
 6360            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6361    }
 6362
 6363    pub fn toggle_centered_layout(
 6364        &mut self,
 6365        _: &ToggleCenteredLayout,
 6366        _: &mut Window,
 6367        cx: &mut Context<Self>,
 6368    ) {
 6369        self.centered_layout = !self.centered_layout;
 6370        if let Some(database_id) = self.database_id() {
 6371            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6372                .detach_and_log_err(cx);
 6373        }
 6374        cx.notify();
 6375    }
 6376
 6377    fn adjust_padding(padding: Option<f32>) -> f32 {
 6378        padding
 6379            .unwrap_or(CenteredPaddingSettings::default().0)
 6380            .clamp(
 6381                CenteredPaddingSettings::MIN_PADDING,
 6382                CenteredPaddingSettings::MAX_PADDING,
 6383            )
 6384    }
 6385
 6386    fn render_dock(
 6387        &self,
 6388        position: DockPosition,
 6389        dock: &Entity<Dock>,
 6390        window: &mut Window,
 6391        cx: &mut App,
 6392    ) -> Option<Div> {
 6393        if self.zoomed_position == Some(position) {
 6394            return None;
 6395        }
 6396
 6397        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6398            let pane = panel.pane(cx)?;
 6399            let follower_states = &self.follower_states;
 6400            leader_border_for_pane(follower_states, &pane, window, cx)
 6401        });
 6402
 6403        Some(
 6404            div()
 6405                .flex()
 6406                .flex_none()
 6407                .overflow_hidden()
 6408                .child(dock.clone())
 6409                .children(leader_border),
 6410        )
 6411    }
 6412
 6413    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 6414        window.root().flatten()
 6415    }
 6416
 6417    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6418        self.zoomed.as_ref()
 6419    }
 6420
 6421    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6422        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6423            return;
 6424        };
 6425        let windows = cx.windows();
 6426        let next_window =
 6427            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6428                || {
 6429                    windows
 6430                        .iter()
 6431                        .cycle()
 6432                        .skip_while(|window| window.window_id() != current_window_id)
 6433                        .nth(1)
 6434                },
 6435            );
 6436
 6437        if let Some(window) = next_window {
 6438            window
 6439                .update(cx, |_, window, _| window.activate_window())
 6440                .ok();
 6441        }
 6442    }
 6443
 6444    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6445        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6446            return;
 6447        };
 6448        let windows = cx.windows();
 6449        let prev_window =
 6450            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6451                || {
 6452                    windows
 6453                        .iter()
 6454                        .rev()
 6455                        .cycle()
 6456                        .skip_while(|window| window.window_id() != current_window_id)
 6457                        .nth(1)
 6458                },
 6459            );
 6460
 6461        if let Some(window) = prev_window {
 6462            window
 6463                .update(cx, |_, window, _| window.activate_window())
 6464                .ok();
 6465        }
 6466    }
 6467
 6468    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6469        if cx.stop_active_drag(window) {
 6470        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6471            dismiss_app_notification(&notification_id, cx);
 6472        } else {
 6473            cx.propagate();
 6474        }
 6475    }
 6476
 6477    fn adjust_dock_size_by_px(
 6478        &mut self,
 6479        panel_size: Pixels,
 6480        dock_pos: DockPosition,
 6481        px: Pixels,
 6482        window: &mut Window,
 6483        cx: &mut Context<Self>,
 6484    ) {
 6485        match dock_pos {
 6486            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6487            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6488            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6489        }
 6490    }
 6491
 6492    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6493        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6494
 6495        self.left_dock.update(cx, |left_dock, cx| {
 6496            if WorkspaceSettings::get_global(cx)
 6497                .resize_all_panels_in_dock
 6498                .contains(&DockPosition::Left)
 6499            {
 6500                left_dock.resize_all_panels(Some(size), window, cx);
 6501            } else {
 6502                left_dock.resize_active_panel(Some(size), window, cx);
 6503            }
 6504        });
 6505        self.clamp_utility_pane_widths(window, cx);
 6506    }
 6507
 6508    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6509        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6510        self.left_dock.read_with(cx, |left_dock, cx| {
 6511            let left_dock_size = left_dock
 6512                .active_panel_size(window, cx)
 6513                .unwrap_or(Pixels::ZERO);
 6514            if left_dock_size + size > self.bounds.right() {
 6515                size = self.bounds.right() - left_dock_size
 6516            }
 6517        });
 6518        self.right_dock.update(cx, |right_dock, cx| {
 6519            if WorkspaceSettings::get_global(cx)
 6520                .resize_all_panels_in_dock
 6521                .contains(&DockPosition::Right)
 6522            {
 6523                right_dock.resize_all_panels(Some(size), window, cx);
 6524            } else {
 6525                right_dock.resize_active_panel(Some(size), window, cx);
 6526            }
 6527        });
 6528        self.clamp_utility_pane_widths(window, cx);
 6529    }
 6530
 6531    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6532        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6533        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6534            if WorkspaceSettings::get_global(cx)
 6535                .resize_all_panels_in_dock
 6536                .contains(&DockPosition::Bottom)
 6537            {
 6538                bottom_dock.resize_all_panels(Some(size), window, cx);
 6539            } else {
 6540                bottom_dock.resize_active_panel(Some(size), window, cx);
 6541            }
 6542        });
 6543        self.clamp_utility_pane_widths(window, cx);
 6544    }
 6545
 6546    fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
 6547        let left_dock_width = self
 6548            .left_dock
 6549            .read(cx)
 6550            .active_panel_size(window, cx)
 6551            .unwrap_or(px(0.0));
 6552        let right_dock_width = self
 6553            .right_dock
 6554            .read(cx)
 6555            .active_panel_size(window, cx)
 6556            .unwrap_or(px(0.0));
 6557        let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
 6558        center_pane_width - px(10.0)
 6559    }
 6560
 6561    fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
 6562        let max_width = self.max_utility_pane_width(window, cx);
 6563
 6564        // Clamp left slot utility pane if it exists
 6565        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
 6566            let current_width = handle.width(cx);
 6567            if current_width > max_width {
 6568                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6569            }
 6570        }
 6571
 6572        // Clamp right slot utility pane if it exists
 6573        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
 6574            let current_width = handle.width(cx);
 6575            if current_width > max_width {
 6576                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6577            }
 6578        }
 6579    }
 6580
 6581    fn toggle_edit_predictions_all_files(
 6582        &mut self,
 6583        _: &ToggleEditPrediction,
 6584        _window: &mut Window,
 6585        cx: &mut Context<Self>,
 6586    ) {
 6587        let fs = self.project().read(cx).fs().clone();
 6588        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6589        update_settings_file(fs, cx, move |file, _| {
 6590            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6591        });
 6592    }
 6593
 6594    pub fn show_worktree_trust_security_modal(
 6595        &mut self,
 6596        toggle: bool,
 6597        window: &mut Window,
 6598        cx: &mut Context<Self>,
 6599    ) {
 6600        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 6601            if toggle {
 6602                security_modal.update(cx, |security_modal, cx| {
 6603                    security_modal.dismiss(cx);
 6604                })
 6605            } else {
 6606                security_modal.update(cx, |security_modal, cx| {
 6607                    security_modal.refresh_restricted_paths(cx);
 6608                });
 6609            }
 6610        } else {
 6611            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 6612                .map(|trusted_worktrees| {
 6613                    trusted_worktrees
 6614                        .read(cx)
 6615                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 6616                })
 6617                .unwrap_or(false);
 6618            if has_restricted_worktrees {
 6619                let project = self.project().read(cx);
 6620                let remote_host = project
 6621                    .remote_connection_options(cx)
 6622                    .map(RemoteHostLocation::from);
 6623                let worktree_store = project.worktree_store().downgrade();
 6624                self.toggle_modal(window, cx, |_, cx| {
 6625                    SecurityModal::new(worktree_store, remote_host, cx)
 6626                });
 6627            }
 6628        }
 6629    }
 6630
 6631    fn update_worktree_data(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) {
 6632        self.update_window_title(window, cx);
 6633        self.serialize_workspace(window, cx);
 6634        // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
 6635        self.update_history(cx);
 6636    }
 6637}
 6638
 6639fn leader_border_for_pane(
 6640    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6641    pane: &Entity<Pane>,
 6642    _: &Window,
 6643    cx: &App,
 6644) -> Option<Div> {
 6645    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6646        if state.pane() == pane {
 6647            Some((*leader_id, state))
 6648        } else {
 6649            None
 6650        }
 6651    })?;
 6652
 6653    let mut leader_color = match leader_id {
 6654        CollaboratorId::PeerId(leader_peer_id) => {
 6655            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6656            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6657
 6658            cx.theme()
 6659                .players()
 6660                .color_for_participant(leader.participant_index.0)
 6661                .cursor
 6662        }
 6663        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6664    };
 6665    leader_color.fade_out(0.3);
 6666    Some(
 6667        div()
 6668            .absolute()
 6669            .size_full()
 6670            .left_0()
 6671            .top_0()
 6672            .border_2()
 6673            .border_color(leader_color),
 6674    )
 6675}
 6676
 6677fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 6678    ZED_WINDOW_POSITION
 6679        .zip(*ZED_WINDOW_SIZE)
 6680        .map(|(position, size)| Bounds {
 6681            origin: position,
 6682            size,
 6683        })
 6684}
 6685
 6686fn open_items(
 6687    serialized_workspace: Option<SerializedWorkspace>,
 6688    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 6689    window: &mut Window,
 6690    cx: &mut Context<Workspace>,
 6691) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 6692    let restored_items = serialized_workspace.map(|serialized_workspace| {
 6693        Workspace::load_workspace(
 6694            serialized_workspace,
 6695            project_paths_to_open
 6696                .iter()
 6697                .map(|(_, project_path)| project_path)
 6698                .cloned()
 6699                .collect(),
 6700            window,
 6701            cx,
 6702        )
 6703    });
 6704
 6705    cx.spawn_in(window, async move |workspace, cx| {
 6706        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 6707
 6708        if let Some(restored_items) = restored_items {
 6709            let restored_items = restored_items.await?;
 6710
 6711            let restored_project_paths = restored_items
 6712                .iter()
 6713                .filter_map(|item| {
 6714                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 6715                        .ok()
 6716                        .flatten()
 6717                })
 6718                .collect::<HashSet<_>>();
 6719
 6720            for restored_item in restored_items {
 6721                opened_items.push(restored_item.map(Ok));
 6722            }
 6723
 6724            project_paths_to_open
 6725                .iter_mut()
 6726                .for_each(|(_, project_path)| {
 6727                    if let Some(project_path_to_open) = project_path
 6728                        && restored_project_paths.contains(project_path_to_open)
 6729                    {
 6730                        *project_path = None;
 6731                    }
 6732                });
 6733        } else {
 6734            for _ in 0..project_paths_to_open.len() {
 6735                opened_items.push(None);
 6736            }
 6737        }
 6738        assert!(opened_items.len() == project_paths_to_open.len());
 6739
 6740        let tasks =
 6741            project_paths_to_open
 6742                .into_iter()
 6743                .enumerate()
 6744                .map(|(ix, (abs_path, project_path))| {
 6745                    let workspace = workspace.clone();
 6746                    cx.spawn(async move |cx| {
 6747                        let file_project_path = project_path?;
 6748                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6749                            workspace.project().update(cx, |project, cx| {
 6750                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6751                            })
 6752                        });
 6753
 6754                        // We only want to open file paths here. If one of the items
 6755                        // here is a directory, it was already opened further above
 6756                        // with a `find_or_create_worktree`.
 6757                        if let Ok(task) = abs_path_task
 6758                            && task.await.is_none_or(|p| p.is_file())
 6759                        {
 6760                            return Some((
 6761                                ix,
 6762                                workspace
 6763                                    .update_in(cx, |workspace, window, cx| {
 6764                                        workspace.open_path(
 6765                                            file_project_path,
 6766                                            None,
 6767                                            true,
 6768                                            window,
 6769                                            cx,
 6770                                        )
 6771                                    })
 6772                                    .log_err()?
 6773                                    .await,
 6774                            ));
 6775                        }
 6776                        None
 6777                    })
 6778                });
 6779
 6780        let tasks = tasks.collect::<Vec<_>>();
 6781
 6782        let tasks = futures::future::join_all(tasks);
 6783        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6784            opened_items[ix] = Some(path_open_result);
 6785        }
 6786
 6787        Ok(opened_items)
 6788    })
 6789}
 6790
 6791enum ActivateInDirectionTarget {
 6792    Pane(Entity<Pane>),
 6793    Dock(Entity<Dock>),
 6794}
 6795
 6796fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6797    workspace
 6798        .update(cx, |workspace, _, cx| {
 6799            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6800                struct DatabaseFailedNotification;
 6801
 6802                workspace.show_notification(
 6803                    NotificationId::unique::<DatabaseFailedNotification>(),
 6804                    cx,
 6805                    |cx| {
 6806                        cx.new(|cx| {
 6807                            MessageNotification::new("Failed to load the database file.", cx)
 6808                                .primary_message("File an Issue")
 6809                                .primary_icon(IconName::Plus)
 6810                                .primary_on_click(|window, cx| {
 6811                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6812                                })
 6813                        })
 6814                    },
 6815                );
 6816            }
 6817        })
 6818        .log_err();
 6819}
 6820
 6821fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6822    if val == 0 {
 6823        ThemeSettings::get_global(cx).ui_font_size(cx)
 6824    } else {
 6825        px(val as f32)
 6826    }
 6827}
 6828
 6829fn adjust_active_dock_size_by_px(
 6830    px: Pixels,
 6831    workspace: &mut Workspace,
 6832    window: &mut Window,
 6833    cx: &mut Context<Workspace>,
 6834) {
 6835    let Some(active_dock) = workspace
 6836        .all_docks()
 6837        .into_iter()
 6838        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6839    else {
 6840        return;
 6841    };
 6842    let dock = active_dock.read(cx);
 6843    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6844        return;
 6845    };
 6846    let dock_pos = dock.position();
 6847    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6848}
 6849
 6850fn adjust_open_docks_size_by_px(
 6851    px: Pixels,
 6852    workspace: &mut Workspace,
 6853    window: &mut Window,
 6854    cx: &mut Context<Workspace>,
 6855) {
 6856    let docks = workspace
 6857        .all_docks()
 6858        .into_iter()
 6859        .filter_map(|dock| {
 6860            if dock.read(cx).is_open() {
 6861                let dock = dock.read(cx);
 6862                let panel_size = dock.active_panel_size(window, cx)?;
 6863                let dock_pos = dock.position();
 6864                Some((panel_size, dock_pos, px))
 6865            } else {
 6866                None
 6867            }
 6868        })
 6869        .collect::<Vec<_>>();
 6870
 6871    docks
 6872        .into_iter()
 6873        .for_each(|(panel_size, dock_pos, offset)| {
 6874            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6875        });
 6876}
 6877
 6878impl Focusable for Workspace {
 6879    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6880        self.active_pane.focus_handle(cx)
 6881    }
 6882}
 6883
 6884#[derive(Clone)]
 6885struct DraggedDock(DockPosition);
 6886
 6887impl Render for DraggedDock {
 6888    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6889        gpui::Empty
 6890    }
 6891}
 6892
 6893impl Render for Workspace {
 6894    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6895        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 6896        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 6897            log::info!("Rendered first frame");
 6898        }
 6899        let mut context = KeyContext::new_with_defaults();
 6900        context.add("Workspace");
 6901        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6902        if let Some(status) = self
 6903            .debugger_provider
 6904            .as_ref()
 6905            .and_then(|provider| provider.active_thread_state(cx))
 6906        {
 6907            match status {
 6908                ThreadStatus::Running | ThreadStatus::Stepping => {
 6909                    context.add("debugger_running");
 6910                }
 6911                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6912                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6913            }
 6914        }
 6915
 6916        if self.left_dock.read(cx).is_open() {
 6917            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6918                context.set("left_dock", active_panel.panel_key());
 6919            }
 6920        }
 6921
 6922        if self.right_dock.read(cx).is_open() {
 6923            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6924                context.set("right_dock", active_panel.panel_key());
 6925            }
 6926        }
 6927
 6928        if self.bottom_dock.read(cx).is_open() {
 6929            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6930                context.set("bottom_dock", active_panel.panel_key());
 6931            }
 6932        }
 6933
 6934        let centered_layout = self.centered_layout
 6935            && self.center.panes().len() == 1
 6936            && self.active_item(cx).is_some();
 6937        let render_padding = |size| {
 6938            (size > 0.0).then(|| {
 6939                div()
 6940                    .h_full()
 6941                    .w(relative(size))
 6942                    .bg(cx.theme().colors().editor_background)
 6943                    .border_color(cx.theme().colors().pane_group_border)
 6944            })
 6945        };
 6946        let paddings = if centered_layout {
 6947            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6948            (
 6949                render_padding(Self::adjust_padding(
 6950                    settings.left_padding.map(|padding| padding.0),
 6951                )),
 6952                render_padding(Self::adjust_padding(
 6953                    settings.right_padding.map(|padding| padding.0),
 6954                )),
 6955            )
 6956        } else {
 6957            (None, None)
 6958        };
 6959        let ui_font = theme::setup_ui_font(window, cx);
 6960
 6961        let theme = cx.theme().clone();
 6962        let colors = theme.colors();
 6963        let notification_entities = self
 6964            .notifications
 6965            .iter()
 6966            .map(|(_, notification)| notification.entity_id())
 6967            .collect::<Vec<_>>();
 6968        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6969
 6970        client_side_decorations(
 6971            self.actions(div(), window, cx)
 6972                .key_context(context)
 6973                .relative()
 6974                .size_full()
 6975                .flex()
 6976                .flex_col()
 6977                .font(ui_font)
 6978                .gap_0()
 6979                .justify_start()
 6980                .items_start()
 6981                .text_color(colors.text)
 6982                .overflow_hidden()
 6983                .children(self.titlebar_item.clone())
 6984                .on_modifiers_changed(move |_, _, cx| {
 6985                    for &id in &notification_entities {
 6986                        cx.notify(id);
 6987                    }
 6988                })
 6989                .child(
 6990                    div()
 6991                        .size_full()
 6992                        .relative()
 6993                        .flex_1()
 6994                        .flex()
 6995                        .flex_col()
 6996                        .child(
 6997                            div()
 6998                                .id("workspace")
 6999                                .bg(colors.background)
 7000                                .relative()
 7001                                .flex_1()
 7002                                .w_full()
 7003                                .flex()
 7004                                .flex_col()
 7005                                .overflow_hidden()
 7006                                .border_t_1()
 7007                                .border_b_1()
 7008                                .border_color(colors.border)
 7009                                .child({
 7010                                    let this = cx.entity();
 7011                                    canvas(
 7012                                        move |bounds, window, cx| {
 7013                                            this.update(cx, |this, cx| {
 7014                                                let bounds_changed = this.bounds != bounds;
 7015                                                this.bounds = bounds;
 7016
 7017                                                if bounds_changed {
 7018                                                    this.left_dock.update(cx, |dock, cx| {
 7019                                                        dock.clamp_panel_size(
 7020                                                            bounds.size.width,
 7021                                                            window,
 7022                                                            cx,
 7023                                                        )
 7024                                                    });
 7025
 7026                                                    this.right_dock.update(cx, |dock, cx| {
 7027                                                        dock.clamp_panel_size(
 7028                                                            bounds.size.width,
 7029                                                            window,
 7030                                                            cx,
 7031                                                        )
 7032                                                    });
 7033
 7034                                                    this.bottom_dock.update(cx, |dock, cx| {
 7035                                                        dock.clamp_panel_size(
 7036                                                            bounds.size.height,
 7037                                                            window,
 7038                                                            cx,
 7039                                                        )
 7040                                                    });
 7041                                                }
 7042                                            })
 7043                                        },
 7044                                        |_, _, _, _| {},
 7045                                    )
 7046                                    .absolute()
 7047                                    .size_full()
 7048                                })
 7049                                .when(self.zoomed.is_none(), |this| {
 7050                                    this.on_drag_move(cx.listener(
 7051                                        move |workspace,
 7052                                              e: &DragMoveEvent<DraggedDock>,
 7053                                              window,
 7054                                              cx| {
 7055                                            if workspace.previous_dock_drag_coordinates
 7056                                                != Some(e.event.position)
 7057                                            {
 7058                                                workspace.previous_dock_drag_coordinates =
 7059                                                    Some(e.event.position);
 7060                                                match e.drag(cx).0 {
 7061                                                    DockPosition::Left => {
 7062                                                        workspace.resize_left_dock(
 7063                                                            e.event.position.x
 7064                                                                - workspace.bounds.left(),
 7065                                                            window,
 7066                                                            cx,
 7067                                                        );
 7068                                                    }
 7069                                                    DockPosition::Right => {
 7070                                                        workspace.resize_right_dock(
 7071                                                            workspace.bounds.right()
 7072                                                                - e.event.position.x,
 7073                                                            window,
 7074                                                            cx,
 7075                                                        );
 7076                                                    }
 7077                                                    DockPosition::Bottom => {
 7078                                                        workspace.resize_bottom_dock(
 7079                                                            workspace.bounds.bottom()
 7080                                                                - e.event.position.y,
 7081                                                            window,
 7082                                                            cx,
 7083                                                        );
 7084                                                    }
 7085                                                };
 7086                                                workspace.serialize_workspace(window, cx);
 7087                                            }
 7088                                        },
 7089                                    ))
 7090                                    .on_drag_move(cx.listener(
 7091                                        move |workspace,
 7092                                              e: &DragMoveEvent<DraggedUtilityPane>,
 7093                                              window,
 7094                                              cx| {
 7095                                            let slot = e.drag(cx).0;
 7096                                            match slot {
 7097                                                UtilityPaneSlot::Left => {
 7098                                                    let left_dock_width = workspace.left_dock.read(cx)
 7099                                                        .active_panel_size(window, cx)
 7100                                                        .unwrap_or(gpui::px(0.0));
 7101                                                    let new_width = e.event.position.x
 7102                                                        - workspace.bounds.left()
 7103                                                        - left_dock_width;
 7104                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7105                                                }
 7106                                                UtilityPaneSlot::Right => {
 7107                                                    let right_dock_width = workspace.right_dock.read(cx)
 7108                                                        .active_panel_size(window, cx)
 7109                                                        .unwrap_or(gpui::px(0.0));
 7110                                                    let new_width = workspace.bounds.right()
 7111                                                        - e.event.position.x
 7112                                                        - right_dock_width;
 7113                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7114                                                }
 7115                                            }
 7116                                        },
 7117                                    ))
 7118                                })
 7119                                .child({
 7120                                    match bottom_dock_layout {
 7121                                        BottomDockLayout::Full => div()
 7122                                            .flex()
 7123                                            .flex_col()
 7124                                            .h_full()
 7125                                            .child(
 7126                                                div()
 7127                                                    .flex()
 7128                                                    .flex_row()
 7129                                                    .flex_1()
 7130                                                    .overflow_hidden()
 7131                                                    .children(self.render_dock(
 7132                                                        DockPosition::Left,
 7133                                                        &self.left_dock,
 7134                                                        window,
 7135                                                        cx,
 7136                                                    ))
 7137                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7138                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7139                                                            this.when(pane.expanded(cx), |this| {
 7140                                                                this.child(
 7141                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7142                                                                )
 7143                                                            })
 7144                                                        })
 7145                                                    })
 7146                                                    .child(
 7147                                                        div()
 7148                                                            .flex()
 7149                                                            .flex_col()
 7150                                                            .flex_1()
 7151                                                            .overflow_hidden()
 7152                                                            .child(
 7153                                                                h_flex()
 7154                                                                    .flex_1()
 7155                                                                    .when_some(
 7156                                                                        paddings.0,
 7157                                                                        |this, p| {
 7158                                                                            this.child(
 7159                                                                                p.border_r_1(),
 7160                                                                            )
 7161                                                                        },
 7162                                                                    )
 7163                                                                    .child(self.center.render(
 7164                                                                        self.zoomed.as_ref(),
 7165                                                                        &PaneRenderContext {
 7166                                                                            follower_states:
 7167                                                                                &self.follower_states,
 7168                                                                            active_call: self.active_call(),
 7169                                                                            active_pane: &self.active_pane,
 7170                                                                            app_state: &self.app_state,
 7171                                                                            project: &self.project,
 7172                                                                            workspace: &self.weak_self,
 7173                                                                        },
 7174                                                                        window,
 7175                                                                        cx,
 7176                                                                    ))
 7177                                                                    .when_some(
 7178                                                                        paddings.1,
 7179                                                                        |this, p| {
 7180                                                                            this.child(
 7181                                                                                p.border_l_1(),
 7182                                                                            )
 7183                                                                        },
 7184                                                                    ),
 7185                                                            ),
 7186                                                    )
 7187                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7188                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7189                                                            this.when(pane.expanded(cx), |this| {
 7190                                                                this.child(
 7191                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7192                                                                )
 7193                                                            })
 7194                                                        })
 7195                                                    })
 7196                                                    .children(self.render_dock(
 7197                                                        DockPosition::Right,
 7198                                                        &self.right_dock,
 7199                                                        window,
 7200                                                        cx,
 7201                                                    )),
 7202                                            )
 7203                                            .child(div().w_full().children(self.render_dock(
 7204                                                DockPosition::Bottom,
 7205                                                &self.bottom_dock,
 7206                                                window,
 7207                                                cx
 7208                                            ))),
 7209
 7210                                        BottomDockLayout::LeftAligned => div()
 7211                                            .flex()
 7212                                            .flex_row()
 7213                                            .h_full()
 7214                                            .child(
 7215                                                div()
 7216                                                    .flex()
 7217                                                    .flex_col()
 7218                                                    .flex_1()
 7219                                                    .h_full()
 7220                                                    .child(
 7221                                                        div()
 7222                                                            .flex()
 7223                                                            .flex_row()
 7224                                                            .flex_1()
 7225                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7226                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7227                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7228                                                                    this.when(pane.expanded(cx), |this| {
 7229                                                                        this.child(
 7230                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7231                                                                        )
 7232                                                                    })
 7233                                                                })
 7234                                                            })
 7235                                                            .child(
 7236                                                                div()
 7237                                                                    .flex()
 7238                                                                    .flex_col()
 7239                                                                    .flex_1()
 7240                                                                    .overflow_hidden()
 7241                                                                    .child(
 7242                                                                        h_flex()
 7243                                                                            .flex_1()
 7244                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7245                                                                            .child(self.center.render(
 7246                                                                                self.zoomed.as_ref(),
 7247                                                                                &PaneRenderContext {
 7248                                                                                    follower_states:
 7249                                                                                        &self.follower_states,
 7250                                                                                    active_call: self.active_call(),
 7251                                                                                    active_pane: &self.active_pane,
 7252                                                                                    app_state: &self.app_state,
 7253                                                                                    project: &self.project,
 7254                                                                                    workspace: &self.weak_self,
 7255                                                                                },
 7256                                                                                window,
 7257                                                                                cx,
 7258                                                                            ))
 7259                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7260                                                                    )
 7261                                                            )
 7262                                                            .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7263                                                                this.when(pane.expanded(cx), |this| {
 7264                                                                    this.child(
 7265                                                                        UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7266                                                                    )
 7267                                                                })
 7268                                                            })
 7269                                                    )
 7270                                                    .child(
 7271                                                        div()
 7272                                                            .w_full()
 7273                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7274                                                    ),
 7275                                            )
 7276                                            .children(self.render_dock(
 7277                                                DockPosition::Right,
 7278                                                &self.right_dock,
 7279                                                window,
 7280                                                cx,
 7281                                            )),
 7282
 7283                                        BottomDockLayout::RightAligned => div()
 7284                                            .flex()
 7285                                            .flex_row()
 7286                                            .h_full()
 7287                                            .children(self.render_dock(
 7288                                                DockPosition::Left,
 7289                                                &self.left_dock,
 7290                                                window,
 7291                                                cx,
 7292                                            ))
 7293                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7294                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7295                                                    this.when(pane.expanded(cx), |this| {
 7296                                                        this.child(
 7297                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7298                                                        )
 7299                                                    })
 7300                                                })
 7301                                            })
 7302                                            .child(
 7303                                                div()
 7304                                                    .flex()
 7305                                                    .flex_col()
 7306                                                    .flex_1()
 7307                                                    .h_full()
 7308                                                    .child(
 7309                                                        div()
 7310                                                            .flex()
 7311                                                            .flex_row()
 7312                                                            .flex_1()
 7313                                                            .child(
 7314                                                                div()
 7315                                                                    .flex()
 7316                                                                    .flex_col()
 7317                                                                    .flex_1()
 7318                                                                    .overflow_hidden()
 7319                                                                    .child(
 7320                                                                        h_flex()
 7321                                                                            .flex_1()
 7322                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7323                                                                            .child(self.center.render(
 7324                                                                                self.zoomed.as_ref(),
 7325                                                                                &PaneRenderContext {
 7326                                                                                    follower_states:
 7327                                                                                        &self.follower_states,
 7328                                                                                    active_call: self.active_call(),
 7329                                                                                    active_pane: &self.active_pane,
 7330                                                                                    app_state: &self.app_state,
 7331                                                                                    project: &self.project,
 7332                                                                                    workspace: &self.weak_self,
 7333                                                                                },
 7334                                                                                window,
 7335                                                                                cx,
 7336                                                                            ))
 7337                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7338                                                                    )
 7339                                                            )
 7340                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7341                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7342                                                                    this.when(pane.expanded(cx), |this| {
 7343                                                                        this.child(
 7344                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7345                                                                        )
 7346                                                                    })
 7347                                                                })
 7348                                                            })
 7349                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7350                                                    )
 7351                                                    .child(
 7352                                                        div()
 7353                                                            .w_full()
 7354                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7355                                                    ),
 7356                                            ),
 7357
 7358                                        BottomDockLayout::Contained => div()
 7359                                            .flex()
 7360                                            .flex_row()
 7361                                            .h_full()
 7362                                            .children(self.render_dock(
 7363                                                DockPosition::Left,
 7364                                                &self.left_dock,
 7365                                                window,
 7366                                                cx,
 7367                                            ))
 7368                                            .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7369                                                this.when(pane.expanded(cx), |this| {
 7370                                                    this.child(
 7371                                                        UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7372                                                    )
 7373                                                })
 7374                                            })
 7375                                            .child(
 7376                                                div()
 7377                                                    .flex()
 7378                                                    .flex_col()
 7379                                                    .flex_1()
 7380                                                    .overflow_hidden()
 7381                                                    .child(
 7382                                                        h_flex()
 7383                                                            .flex_1()
 7384                                                            .when_some(paddings.0, |this, p| {
 7385                                                                this.child(p.border_r_1())
 7386                                                            })
 7387                                                            .child(self.center.render(
 7388                                                                self.zoomed.as_ref(),
 7389                                                                &PaneRenderContext {
 7390                                                                    follower_states:
 7391                                                                        &self.follower_states,
 7392                                                                    active_call: self.active_call(),
 7393                                                                    active_pane: &self.active_pane,
 7394                                                                    app_state: &self.app_state,
 7395                                                                    project: &self.project,
 7396                                                                    workspace: &self.weak_self,
 7397                                                                },
 7398                                                                window,
 7399                                                                cx,
 7400                                                            ))
 7401                                                            .when_some(paddings.1, |this, p| {
 7402                                                                this.child(p.border_l_1())
 7403                                                            }),
 7404                                                    )
 7405                                                    .children(self.render_dock(
 7406                                                        DockPosition::Bottom,
 7407                                                        &self.bottom_dock,
 7408                                                        window,
 7409                                                        cx,
 7410                                                    )),
 7411                                            )
 7412                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7413                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7414                                                    this.when(pane.expanded(cx), |this| {
 7415                                                        this.child(
 7416                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7417                                                        )
 7418                                                    })
 7419                                                })
 7420                                            })
 7421                                            .children(self.render_dock(
 7422                                                DockPosition::Right,
 7423                                                &self.right_dock,
 7424                                                window,
 7425                                                cx,
 7426                                            )),
 7427                                    }
 7428                                })
 7429                                .children(self.zoomed.as_ref().and_then(|view| {
 7430                                    let zoomed_view = view.upgrade()?;
 7431                                    let div = div()
 7432                                        .occlude()
 7433                                        .absolute()
 7434                                        .overflow_hidden()
 7435                                        .border_color(colors.border)
 7436                                        .bg(colors.background)
 7437                                        .child(zoomed_view)
 7438                                        .inset_0()
 7439                                        .shadow_lg();
 7440
 7441                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7442                                       return Some(div);
 7443                                    }
 7444
 7445                                    Some(match self.zoomed_position {
 7446                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7447                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7448                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7449                                        None => {
 7450                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7451                                        }
 7452                                    })
 7453                                }))
 7454                                .children(self.render_notifications(window, cx)),
 7455                        )
 7456                        .when(self.status_bar_visible(cx), |parent| {
 7457                            parent.child(self.status_bar.clone())
 7458                        })
 7459                        .child(self.modal_layer.clone())
 7460                        .child(self.toast_layer.clone()),
 7461                ),
 7462            window,
 7463            cx,
 7464        )
 7465    }
 7466}
 7467
 7468impl WorkspaceStore {
 7469    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7470        Self {
 7471            workspaces: Default::default(),
 7472            _subscriptions: vec![
 7473                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7474                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7475            ],
 7476            client,
 7477        }
 7478    }
 7479
 7480    pub fn update_followers(
 7481        &self,
 7482        project_id: Option<u64>,
 7483        update: proto::update_followers::Variant,
 7484        cx: &App,
 7485    ) -> Option<()> {
 7486        let active_call = ActiveCall::try_global(cx)?;
 7487        let room_id = active_call.read(cx).room()?.read(cx).id();
 7488        self.client
 7489            .send(proto::UpdateFollowers {
 7490                room_id,
 7491                project_id,
 7492                variant: Some(update),
 7493            })
 7494            .log_err()
 7495    }
 7496
 7497    pub async fn handle_follow(
 7498        this: Entity<Self>,
 7499        envelope: TypedEnvelope<proto::Follow>,
 7500        mut cx: AsyncApp,
 7501    ) -> Result<proto::FollowResponse> {
 7502        this.update(&mut cx, |this, cx| {
 7503            let follower = Follower {
 7504                project_id: envelope.payload.project_id,
 7505                peer_id: envelope.original_sender_id()?,
 7506            };
 7507
 7508            let mut response = proto::FollowResponse::default();
 7509            this.workspaces.retain(|workspace| {
 7510                workspace
 7511                    .update(cx, |workspace, window, cx| {
 7512                        let handler_response =
 7513                            workspace.handle_follow(follower.project_id, window, cx);
 7514                        if let Some(active_view) = handler_response.active_view
 7515                            && workspace.project.read(cx).remote_id() == follower.project_id
 7516                        {
 7517                            response.active_view = Some(active_view)
 7518                        }
 7519                    })
 7520                    .is_ok()
 7521            });
 7522
 7523            Ok(response)
 7524        })?
 7525    }
 7526
 7527    async fn handle_update_followers(
 7528        this: Entity<Self>,
 7529        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7530        mut cx: AsyncApp,
 7531    ) -> Result<()> {
 7532        let leader_id = envelope.original_sender_id()?;
 7533        let update = envelope.payload;
 7534
 7535        this.update(&mut cx, |this, cx| {
 7536            this.workspaces.retain(|workspace| {
 7537                workspace
 7538                    .update(cx, |workspace, window, cx| {
 7539                        let project_id = workspace.project.read(cx).remote_id();
 7540                        if update.project_id != project_id && update.project_id.is_some() {
 7541                            return;
 7542                        }
 7543                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 7544                    })
 7545                    .is_ok()
 7546            });
 7547            Ok(())
 7548        })?
 7549    }
 7550
 7551    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 7552        &self.workspaces
 7553    }
 7554}
 7555
 7556impl ViewId {
 7557    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7558        Ok(Self {
 7559            creator: message
 7560                .creator
 7561                .map(CollaboratorId::PeerId)
 7562                .context("creator is missing")?,
 7563            id: message.id,
 7564        })
 7565    }
 7566
 7567    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7568        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7569            Some(proto::ViewId {
 7570                creator: Some(peer_id),
 7571                id: self.id,
 7572            })
 7573        } else {
 7574            None
 7575        }
 7576    }
 7577}
 7578
 7579impl FollowerState {
 7580    fn pane(&self) -> &Entity<Pane> {
 7581        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 7582    }
 7583}
 7584
 7585pub trait WorkspaceHandle {
 7586    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 7587}
 7588
 7589impl WorkspaceHandle for Entity<Workspace> {
 7590    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 7591        self.read(cx)
 7592            .worktrees(cx)
 7593            .flat_map(|worktree| {
 7594                let worktree_id = worktree.read(cx).id();
 7595                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 7596                    worktree_id,
 7597                    path: f.path.clone(),
 7598                })
 7599            })
 7600            .collect::<Vec<_>>()
 7601    }
 7602}
 7603
 7604pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 7605    DB.last_workspace().await.log_err().flatten()
 7606}
 7607
 7608pub fn last_session_workspace_locations(
 7609    last_session_id: &str,
 7610    last_session_window_stack: Option<Vec<WindowId>>,
 7611) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 7612    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 7613        .log_err()
 7614}
 7615
 7616actions!(
 7617    collab,
 7618    [
 7619        /// Opens the channel notes for the current call.
 7620        ///
 7621        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 7622        /// channel in the collab panel.
 7623        ///
 7624        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 7625        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7626        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7627        OpenChannelNotes,
 7628        /// Mutes your microphone.
 7629        Mute,
 7630        /// Deafens yourself (mute both microphone and speakers).
 7631        Deafen,
 7632        /// Leaves the current call.
 7633        LeaveCall,
 7634        /// Shares the current project with collaborators.
 7635        ShareProject,
 7636        /// Shares your screen with collaborators.
 7637        ScreenShare,
 7638        /// Copies the current room name and session id for debugging purposes.
 7639        CopyRoomId,
 7640    ]
 7641);
 7642actions!(
 7643    zed,
 7644    [
 7645        /// Opens the Zed log file.
 7646        OpenLog,
 7647        /// Reveals the Zed log file in the system file manager.
 7648        RevealLogInFileManager
 7649    ]
 7650);
 7651
 7652async fn join_channel_internal(
 7653    channel_id: ChannelId,
 7654    app_state: &Arc<AppState>,
 7655    requesting_window: Option<WindowHandle<Workspace>>,
 7656    active_call: &Entity<ActiveCall>,
 7657    cx: &mut AsyncApp,
 7658) -> Result<bool> {
 7659    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7660        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7661            return (false, None);
 7662        };
 7663
 7664        let already_in_channel = room.channel_id() == Some(channel_id);
 7665        let should_prompt = room.is_sharing_project()
 7666            && !room.remote_participants().is_empty()
 7667            && !already_in_channel;
 7668        let open_room = if already_in_channel {
 7669            active_call.room().cloned()
 7670        } else {
 7671            None
 7672        };
 7673        (should_prompt, open_room)
 7674    })?;
 7675
 7676    if let Some(room) = open_room {
 7677        let task = room.update(cx, |room, cx| {
 7678            if let Some((project, host)) = room.most_active_project(cx) {
 7679                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7680            }
 7681
 7682            None
 7683        })?;
 7684        if let Some(task) = task {
 7685            task.await?;
 7686        }
 7687        return anyhow::Ok(true);
 7688    }
 7689
 7690    if should_prompt {
 7691        if let Some(workspace) = requesting_window {
 7692            let answer = workspace
 7693                .update(cx, |_, window, cx| {
 7694                    window.prompt(
 7695                        PromptLevel::Warning,
 7696                        "Do you want to switch channels?",
 7697                        Some("Leaving this call will unshare your current project."),
 7698                        &["Yes, Join Channel", "Cancel"],
 7699                        cx,
 7700                    )
 7701                })?
 7702                .await;
 7703
 7704            if answer == Ok(1) {
 7705                return Ok(false);
 7706            }
 7707        } else {
 7708            return Ok(false); // unreachable!() hopefully
 7709        }
 7710    }
 7711
 7712    let client = cx.update(|cx| active_call.read(cx).client())?;
 7713
 7714    let mut client_status = client.status();
 7715
 7716    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7717    'outer: loop {
 7718        let Some(status) = client_status.recv().await else {
 7719            anyhow::bail!("error connecting");
 7720        };
 7721
 7722        match status {
 7723            Status::Connecting
 7724            | Status::Authenticating
 7725            | Status::Authenticated
 7726            | Status::Reconnecting
 7727            | Status::Reauthenticating
 7728            | Status::Reauthenticated => continue,
 7729            Status::Connected { .. } => break 'outer,
 7730            Status::SignedOut | Status::AuthenticationError => {
 7731                return Err(ErrorCode::SignedOut.into());
 7732            }
 7733            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7734            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7735                return Err(ErrorCode::Disconnected.into());
 7736            }
 7737        }
 7738    }
 7739
 7740    let room = active_call
 7741        .update(cx, |active_call, cx| {
 7742            active_call.join_channel(channel_id, cx)
 7743        })?
 7744        .await?;
 7745
 7746    let Some(room) = room else {
 7747        return anyhow::Ok(true);
 7748    };
 7749
 7750    room.update(cx, |room, _| room.room_update_completed())?
 7751        .await;
 7752
 7753    let task = room.update(cx, |room, cx| {
 7754        if let Some((project, host)) = room.most_active_project(cx) {
 7755            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7756        }
 7757
 7758        // If you are the first to join a channel, see if you should share your project.
 7759        if room.remote_participants().is_empty()
 7760            && !room.local_participant_is_guest()
 7761            && let Some(workspace) = requesting_window
 7762        {
 7763            let project = workspace.update(cx, |workspace, _, cx| {
 7764                let project = workspace.project.read(cx);
 7765
 7766                if !CallSettings::get_global(cx).share_on_join {
 7767                    return None;
 7768                }
 7769
 7770                if (project.is_local() || project.is_via_remote_server())
 7771                    && project.visible_worktrees(cx).any(|tree| {
 7772                        tree.read(cx)
 7773                            .root_entry()
 7774                            .is_some_and(|entry| entry.is_dir())
 7775                    })
 7776                {
 7777                    Some(workspace.project.clone())
 7778                } else {
 7779                    None
 7780                }
 7781            });
 7782            if let Ok(Some(project)) = project {
 7783                return Some(cx.spawn(async move |room, cx| {
 7784                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7785                        .await?;
 7786                    Ok(())
 7787                }));
 7788            }
 7789        }
 7790
 7791        None
 7792    })?;
 7793    if let Some(task) = task {
 7794        task.await?;
 7795        return anyhow::Ok(true);
 7796    }
 7797    anyhow::Ok(false)
 7798}
 7799
 7800pub fn join_channel(
 7801    channel_id: ChannelId,
 7802    app_state: Arc<AppState>,
 7803    requesting_window: Option<WindowHandle<Workspace>>,
 7804    cx: &mut App,
 7805) -> Task<Result<()>> {
 7806    let active_call = ActiveCall::global(cx);
 7807    cx.spawn(async move |cx| {
 7808        let result =
 7809            join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
 7810                .await;
 7811
 7812        // join channel succeeded, and opened a window
 7813        if matches!(result, Ok(true)) {
 7814            return anyhow::Ok(());
 7815        }
 7816
 7817        // find an existing workspace to focus and show call controls
 7818        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 7819        if active_window.is_none() {
 7820            // no open workspaces, make one to show the error in (blergh)
 7821            let (window_handle, _) = cx
 7822                .update(|cx| {
 7823                    Workspace::new_local(
 7824                        vec![],
 7825                        app_state.clone(),
 7826                        requesting_window,
 7827                        None,
 7828                        None,
 7829                        cx,
 7830                    )
 7831                })?
 7832                .await?;
 7833
 7834            if result.is_ok() {
 7835                cx.update(|cx| {
 7836                    cx.dispatch_action(&OpenChannelNotes);
 7837                })
 7838                .log_err();
 7839            }
 7840
 7841            active_window = Some(window_handle);
 7842        }
 7843
 7844        if let Err(err) = result {
 7845            log::error!("failed to join channel: {}", err);
 7846            if let Some(active_window) = active_window {
 7847                active_window
 7848                    .update(cx, |_, window, cx| {
 7849                        let detail: SharedString = match err.error_code() {
 7850                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 7851                            ErrorCode::UpgradeRequired => concat!(
 7852                                "Your are running an unsupported version of Zed. ",
 7853                                "Please update to continue."
 7854                            )
 7855                            .into(),
 7856                            ErrorCode::NoSuchChannel => concat!(
 7857                                "No matching channel was found. ",
 7858                                "Please check the link and try again."
 7859                            )
 7860                            .into(),
 7861                            ErrorCode::Forbidden => concat!(
 7862                                "This channel is private, and you do not have access. ",
 7863                                "Please ask someone to add you and try again."
 7864                            )
 7865                            .into(),
 7866                            ErrorCode::Disconnected => {
 7867                                "Please check your internet connection and try again.".into()
 7868                            }
 7869                            _ => format!("{}\n\nPlease try again.", err).into(),
 7870                        };
 7871                        window.prompt(
 7872                            PromptLevel::Critical,
 7873                            "Failed to join channel",
 7874                            Some(&detail),
 7875                            &["Ok"],
 7876                            cx,
 7877                        )
 7878                    })?
 7879                    .await
 7880                    .ok();
 7881            }
 7882        }
 7883
 7884        // return ok, we showed the error to the user.
 7885        anyhow::Ok(())
 7886    })
 7887}
 7888
 7889pub async fn get_any_active_workspace(
 7890    app_state: Arc<AppState>,
 7891    mut cx: AsyncApp,
 7892) -> anyhow::Result<WindowHandle<Workspace>> {
 7893    // find an existing workspace to focus and show call controls
 7894    let active_window = activate_any_workspace_window(&mut cx);
 7895    if active_window.is_none() {
 7896        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))?
 7897            .await?;
 7898    }
 7899    activate_any_workspace_window(&mut cx).context("could not open zed")
 7900}
 7901
 7902fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7903    cx.update(|cx| {
 7904        if let Some(workspace_window) = cx
 7905            .active_window()
 7906            .and_then(|window| window.downcast::<Workspace>())
 7907        {
 7908            return Some(workspace_window);
 7909        }
 7910
 7911        for window in cx.windows() {
 7912            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7913                workspace_window
 7914                    .update(cx, |_, window, _| window.activate_window())
 7915                    .ok();
 7916                return Some(workspace_window);
 7917            }
 7918        }
 7919        None
 7920    })
 7921    .ok()
 7922    .flatten()
 7923}
 7924
 7925pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7926    cx.windows()
 7927        .into_iter()
 7928        .filter_map(|window| window.downcast::<Workspace>())
 7929        .filter(|workspace| {
 7930            workspace
 7931                .read(cx)
 7932                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7933        })
 7934        .collect()
 7935}
 7936
 7937#[derive(Default)]
 7938pub struct OpenOptions {
 7939    pub visible: Option<OpenVisible>,
 7940    pub focus: Option<bool>,
 7941    pub open_new_workspace: Option<bool>,
 7942    pub prefer_focused_window: bool,
 7943    pub replace_window: Option<WindowHandle<Workspace>>,
 7944    pub env: Option<HashMap<String, String>>,
 7945}
 7946
 7947#[allow(clippy::type_complexity)]
 7948pub fn open_paths(
 7949    abs_paths: &[PathBuf],
 7950    app_state: Arc<AppState>,
 7951    open_options: OpenOptions,
 7952    cx: &mut App,
 7953) -> Task<
 7954    anyhow::Result<(
 7955        WindowHandle<Workspace>,
 7956        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7957    )>,
 7958> {
 7959    let abs_paths = abs_paths.to_vec();
 7960    let mut existing = None;
 7961    let mut best_match = None;
 7962    let mut open_visible = OpenVisible::All;
 7963    #[cfg(target_os = "windows")]
 7964    let wsl_path = abs_paths
 7965        .iter()
 7966        .find_map(|p| util::paths::WslPath::from_path(p));
 7967
 7968    cx.spawn(async move |cx| {
 7969        if open_options.open_new_workspace != Some(true) {
 7970            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7971            let all_metadatas = futures::future::join_all(all_paths)
 7972                .await
 7973                .into_iter()
 7974                .filter_map(|result| result.ok().flatten())
 7975                .collect::<Vec<_>>();
 7976
 7977            cx.update(|cx| {
 7978                for window in local_workspace_windows(cx) {
 7979                    if let Ok(workspace) = window.read(cx) {
 7980                        let m = workspace.project.read(cx).visibility_for_paths(
 7981                            &abs_paths,
 7982                            &all_metadatas,
 7983                            open_options.open_new_workspace == None,
 7984                            cx,
 7985                        );
 7986                        if m > best_match {
 7987                            existing = Some(window);
 7988                            best_match = m;
 7989                        } else if best_match.is_none()
 7990                            && open_options.open_new_workspace == Some(false)
 7991                        {
 7992                            existing = Some(window)
 7993                        }
 7994                    }
 7995                }
 7996            })?;
 7997
 7998            if open_options.open_new_workspace.is_none()
 7999                && (existing.is_none() || open_options.prefer_focused_window)
 8000                && all_metadatas.iter().all(|file| !file.is_dir)
 8001            {
 8002                cx.update(|cx| {
 8003                    if let Some(window) = cx
 8004                        .active_window()
 8005                        .and_then(|window| window.downcast::<Workspace>())
 8006                        && let Ok(workspace) = window.read(cx)
 8007                    {
 8008                        let project = workspace.project().read(cx);
 8009                        if project.is_local() && !project.is_via_collab() {
 8010                            existing = Some(window);
 8011                            open_visible = OpenVisible::None;
 8012                            return;
 8013                        }
 8014                    }
 8015                    for window in local_workspace_windows(cx) {
 8016                        if let Ok(workspace) = window.read(cx) {
 8017                            let project = workspace.project().read(cx);
 8018                            if project.is_via_collab() {
 8019                                continue;
 8020                            }
 8021                            existing = Some(window);
 8022                            open_visible = OpenVisible::None;
 8023                            break;
 8024                        }
 8025                    }
 8026                })?;
 8027            }
 8028        }
 8029
 8030        let result = if let Some(existing) = existing {
 8031            let open_task = existing
 8032                .update(cx, |workspace, window, cx| {
 8033                    window.activate_window();
 8034                    workspace.open_paths(
 8035                        abs_paths,
 8036                        OpenOptions {
 8037                            visible: Some(open_visible),
 8038                            ..Default::default()
 8039                        },
 8040                        None,
 8041                        window,
 8042                        cx,
 8043                    )
 8044                })?
 8045                .await;
 8046
 8047            _ = existing.update(cx, |workspace, _, cx| {
 8048                for item in open_task.iter().flatten() {
 8049                    if let Err(e) = item {
 8050                        workspace.show_error(&e, cx);
 8051                    }
 8052                }
 8053            });
 8054
 8055            Ok((existing, open_task))
 8056        } else {
 8057            cx.update(move |cx| {
 8058                Workspace::new_local(
 8059                    abs_paths,
 8060                    app_state.clone(),
 8061                    open_options.replace_window,
 8062                    open_options.env,
 8063                    None,
 8064                    cx,
 8065                )
 8066            })?
 8067            .await
 8068        };
 8069
 8070        #[cfg(target_os = "windows")]
 8071        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8072            && let Ok((workspace, _)) = &result
 8073        {
 8074            workspace
 8075                .update(cx, move |workspace, _window, cx| {
 8076                    struct OpenInWsl;
 8077                    workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8078                        let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8079                        let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8080                        cx.new(move |cx| {
 8081                            MessageNotification::new(msg, cx)
 8082                                .primary_message("Open in WSL")
 8083                                .primary_icon(IconName::FolderOpen)
 8084                                .primary_on_click(move |window, cx| {
 8085                                    window.dispatch_action(Box::new(remote::OpenWslPath {
 8086                                            distro: remote::WslConnectionOptions {
 8087                                                    distro_name: distro.clone(),
 8088                                                user: None,
 8089                                            },
 8090                                            paths: vec![path.clone().into()],
 8091                                        }), cx)
 8092                                })
 8093                        })
 8094                    });
 8095                })
 8096                .unwrap();
 8097        };
 8098        result
 8099    })
 8100}
 8101
 8102pub fn open_new(
 8103    open_options: OpenOptions,
 8104    app_state: Arc<AppState>,
 8105    cx: &mut App,
 8106    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8107) -> Task<anyhow::Result<()>> {
 8108    let task = Workspace::new_local(
 8109        Vec::new(),
 8110        app_state,
 8111        None,
 8112        open_options.env,
 8113        Some(Box::new(init)),
 8114        cx,
 8115    );
 8116    cx.spawn(async move |_cx| {
 8117        let (_workspace, _opened_paths) = task.await?;
 8118        // Init callback is called synchronously during workspace creation
 8119        Ok(())
 8120    })
 8121}
 8122
 8123pub fn create_and_open_local_file(
 8124    path: &'static Path,
 8125    window: &mut Window,
 8126    cx: &mut Context<Workspace>,
 8127    default_content: impl 'static + Send + FnOnce() -> Rope,
 8128) -> Task<Result<Box<dyn ItemHandle>>> {
 8129    cx.spawn_in(window, async move |workspace, cx| {
 8130        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8131        if !fs.is_file(path).await {
 8132            fs.create_file(path, Default::default()).await?;
 8133            fs.save(path, &default_content(), Default::default())
 8134                .await?;
 8135        }
 8136
 8137        let mut items = workspace
 8138            .update_in(cx, |workspace, window, cx| {
 8139                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 8140                    workspace.open_paths(
 8141                        vec![path.to_path_buf()],
 8142                        OpenOptions {
 8143                            visible: Some(OpenVisible::None),
 8144                            ..Default::default()
 8145                        },
 8146                        None,
 8147                        window,
 8148                        cx,
 8149                    )
 8150                })
 8151            })?
 8152            .await?
 8153            .await;
 8154
 8155        let item = items.pop().flatten();
 8156        item.with_context(|| format!("path {path:?} is not a file"))?
 8157    })
 8158}
 8159
 8160pub fn open_remote_project_with_new_connection(
 8161    window: WindowHandle<Workspace>,
 8162    remote_connection: Arc<dyn RemoteConnection>,
 8163    cancel_rx: oneshot::Receiver<()>,
 8164    delegate: Arc<dyn RemoteClientDelegate>,
 8165    app_state: Arc<AppState>,
 8166    paths: Vec<PathBuf>,
 8167    cx: &mut App,
 8168) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8169    cx.spawn(async move |cx| {
 8170        let (workspace_id, serialized_workspace) =
 8171            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8172                .await?;
 8173
 8174        let session = match cx
 8175            .update(|cx| {
 8176                remote::RemoteClient::new(
 8177                    ConnectionIdentifier::Workspace(workspace_id.0),
 8178                    remote_connection,
 8179                    cancel_rx,
 8180                    delegate,
 8181                    cx,
 8182                )
 8183            })?
 8184            .await?
 8185        {
 8186            Some(result) => result,
 8187            None => return Ok(Vec::new()),
 8188        };
 8189
 8190        let project = cx.update(|cx| {
 8191            project::Project::remote(
 8192                session,
 8193                app_state.client.clone(),
 8194                app_state.node_runtime.clone(),
 8195                app_state.user_store.clone(),
 8196                app_state.languages.clone(),
 8197                app_state.fs.clone(),
 8198                true,
 8199                cx,
 8200            )
 8201        })?;
 8202
 8203        open_remote_project_inner(
 8204            project,
 8205            paths,
 8206            workspace_id,
 8207            serialized_workspace,
 8208            app_state,
 8209            window,
 8210            cx,
 8211        )
 8212        .await
 8213    })
 8214}
 8215
 8216pub fn open_remote_project_with_existing_connection(
 8217    connection_options: RemoteConnectionOptions,
 8218    project: Entity<Project>,
 8219    paths: Vec<PathBuf>,
 8220    app_state: Arc<AppState>,
 8221    window: WindowHandle<Workspace>,
 8222    cx: &mut AsyncApp,
 8223) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8224    cx.spawn(async move |cx| {
 8225        let (workspace_id, serialized_workspace) =
 8226            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 8227
 8228        open_remote_project_inner(
 8229            project,
 8230            paths,
 8231            workspace_id,
 8232            serialized_workspace,
 8233            app_state,
 8234            window,
 8235            cx,
 8236        )
 8237        .await
 8238    })
 8239}
 8240
 8241async fn open_remote_project_inner(
 8242    project: Entity<Project>,
 8243    paths: Vec<PathBuf>,
 8244    workspace_id: WorkspaceId,
 8245    serialized_workspace: Option<SerializedWorkspace>,
 8246    app_state: Arc<AppState>,
 8247    window: WindowHandle<Workspace>,
 8248    cx: &mut AsyncApp,
 8249) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 8250    let toolchains = DB.toolchains(workspace_id).await?;
 8251    for (toolchain, worktree_path, path) in toolchains {
 8252        project
 8253            .update(cx, |this, cx| {
 8254                let Some(worktree_id) =
 8255                    this.find_worktree(&worktree_path, cx)
 8256                        .and_then(|(worktree, rel_path)| {
 8257                            if rel_path.is_empty() {
 8258                                Some(worktree.read(cx).id())
 8259                            } else {
 8260                                None
 8261                            }
 8262                        })
 8263                else {
 8264                    return Task::ready(None);
 8265                };
 8266
 8267                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 8268            })?
 8269            .await;
 8270    }
 8271    let mut project_paths_to_open = vec![];
 8272    let mut project_path_errors = vec![];
 8273
 8274    for path in paths {
 8275        let result = cx
 8276            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 8277            .await;
 8278        match result {
 8279            Ok((_, project_path)) => {
 8280                project_paths_to_open.push((path.clone(), Some(project_path)));
 8281            }
 8282            Err(error) => {
 8283                project_path_errors.push(error);
 8284            }
 8285        };
 8286    }
 8287
 8288    if project_paths_to_open.is_empty() {
 8289        return Err(project_path_errors.pop().context("no paths given")?);
 8290    }
 8291
 8292    if let Some(detach_session_task) = window
 8293        .update(cx, |_workspace, window, cx| {
 8294            cx.spawn_in(window, async move |this, cx| {
 8295                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 8296            })
 8297        })
 8298        .ok()
 8299    {
 8300        detach_session_task.await.ok();
 8301    }
 8302
 8303    cx.update_window(window.into(), |_, window, cx| {
 8304        window.replace_root(cx, |window, cx| {
 8305            telemetry::event!("SSH Project Opened");
 8306
 8307            let mut workspace =
 8308                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 8309            workspace.update_history(cx);
 8310
 8311            if let Some(ref serialized) = serialized_workspace {
 8312                workspace.centered_layout = serialized.centered_layout;
 8313            }
 8314
 8315            workspace
 8316        });
 8317    })?;
 8318
 8319    let items = window
 8320        .update(cx, |_, window, cx| {
 8321            window.activate_window();
 8322            open_items(serialized_workspace, project_paths_to_open, window, cx)
 8323        })?
 8324        .await?;
 8325
 8326    window.update(cx, |workspace, _, cx| {
 8327        for error in project_path_errors {
 8328            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 8329                if let Some(path) = error.error_tag("path") {
 8330                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 8331                }
 8332            } else {
 8333                workspace.show_error(&error, cx)
 8334            }
 8335        }
 8336    })?;
 8337
 8338    Ok(items.into_iter().map(|item| item?.ok()).collect())
 8339}
 8340
 8341fn deserialize_remote_project(
 8342    connection_options: RemoteConnectionOptions,
 8343    paths: Vec<PathBuf>,
 8344    cx: &AsyncApp,
 8345) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 8346    cx.background_spawn(async move {
 8347        let remote_connection_id = persistence::DB
 8348            .get_or_create_remote_connection(connection_options)
 8349            .await?;
 8350
 8351        let serialized_workspace =
 8352            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8353
 8354        let workspace_id = if let Some(workspace_id) =
 8355            serialized_workspace.as_ref().map(|workspace| workspace.id)
 8356        {
 8357            workspace_id
 8358        } else {
 8359            persistence::DB.next_id().await?
 8360        };
 8361
 8362        Ok((workspace_id, serialized_workspace))
 8363    })
 8364}
 8365
 8366pub fn join_in_room_project(
 8367    project_id: u64,
 8368    follow_user_id: u64,
 8369    app_state: Arc<AppState>,
 8370    cx: &mut App,
 8371) -> Task<Result<()>> {
 8372    let windows = cx.windows();
 8373    cx.spawn(async move |cx| {
 8374        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 8375            window_handle
 8376                .downcast::<Workspace>()
 8377                .and_then(|window_handle| {
 8378                    window_handle
 8379                        .update(cx, |workspace, _window, cx| {
 8380                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 8381                                Some(window_handle)
 8382                            } else {
 8383                                None
 8384                            }
 8385                        })
 8386                        .unwrap_or(None)
 8387                })
 8388        });
 8389
 8390        let workspace = if let Some(existing_workspace) = existing_workspace {
 8391            existing_workspace
 8392        } else {
 8393            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 8394            let room = active_call
 8395                .read_with(cx, |call, _| call.room().cloned())?
 8396                .context("not in a call")?;
 8397            let project = room
 8398                .update(cx, |room, cx| {
 8399                    room.join_project(
 8400                        project_id,
 8401                        app_state.languages.clone(),
 8402                        app_state.fs.clone(),
 8403                        cx,
 8404                    )
 8405                })?
 8406                .await?;
 8407
 8408            let window_bounds_override = window_bounds_env_override();
 8409            cx.update(|cx| {
 8410                let mut options = (app_state.build_window_options)(None, cx);
 8411                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 8412                cx.open_window(options, |window, cx| {
 8413                    cx.new(|cx| {
 8414                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 8415                    })
 8416                })
 8417            })??
 8418        };
 8419
 8420        workspace.update(cx, |workspace, window, cx| {
 8421            cx.activate(true);
 8422            window.activate_window();
 8423
 8424            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 8425                let follow_peer_id = room
 8426                    .read(cx)
 8427                    .remote_participants()
 8428                    .iter()
 8429                    .find(|(_, participant)| participant.user.id == follow_user_id)
 8430                    .map(|(_, p)| p.peer_id)
 8431                    .or_else(|| {
 8432                        // If we couldn't follow the given user, follow the host instead.
 8433                        let collaborator = workspace
 8434                            .project()
 8435                            .read(cx)
 8436                            .collaborators()
 8437                            .values()
 8438                            .find(|collaborator| collaborator.is_host)?;
 8439                        Some(collaborator.peer_id)
 8440                    });
 8441
 8442                if let Some(follow_peer_id) = follow_peer_id {
 8443                    workspace.follow(follow_peer_id, window, cx);
 8444                }
 8445            }
 8446        })?;
 8447
 8448        anyhow::Ok(())
 8449    })
 8450}
 8451
 8452pub fn reload(cx: &mut App) {
 8453    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 8454    let mut workspace_windows = cx
 8455        .windows()
 8456        .into_iter()
 8457        .filter_map(|window| window.downcast::<Workspace>())
 8458        .collect::<Vec<_>>();
 8459
 8460    // If multiple windows have unsaved changes, and need a save prompt,
 8461    // prompt in the active window before switching to a different window.
 8462    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 8463
 8464    let mut prompt = None;
 8465    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 8466        prompt = window
 8467            .update(cx, |_, window, cx| {
 8468                window.prompt(
 8469                    PromptLevel::Info,
 8470                    "Are you sure you want to restart?",
 8471                    None,
 8472                    &["Restart", "Cancel"],
 8473                    cx,
 8474                )
 8475            })
 8476            .ok();
 8477    }
 8478
 8479    cx.spawn(async move |cx| {
 8480        if let Some(prompt) = prompt {
 8481            let answer = prompt.await?;
 8482            if answer != 0 {
 8483                return Ok(());
 8484            }
 8485        }
 8486
 8487        // If the user cancels any save prompt, then keep the app open.
 8488        for window in workspace_windows {
 8489            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 8490                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 8491            }) && !should_close.await?
 8492            {
 8493                return Ok(());
 8494            }
 8495        }
 8496        cx.update(|cx| cx.restart())
 8497    })
 8498    .detach_and_log_err(cx);
 8499}
 8500
 8501fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 8502    let mut parts = value.split(',');
 8503    let x: usize = parts.next()?.parse().ok()?;
 8504    let y: usize = parts.next()?.parse().ok()?;
 8505    Some(point(px(x as f32), px(y as f32)))
 8506}
 8507
 8508fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 8509    let mut parts = value.split(',');
 8510    let width: usize = parts.next()?.parse().ok()?;
 8511    let height: usize = parts.next()?.parse().ok()?;
 8512    Some(size(px(width as f32), px(height as f32)))
 8513}
 8514
 8515/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 8516pub fn client_side_decorations(
 8517    element: impl IntoElement,
 8518    window: &mut Window,
 8519    cx: &mut App,
 8520) -> Stateful<Div> {
 8521    const BORDER_SIZE: Pixels = px(1.0);
 8522    let decorations = window.window_decorations();
 8523
 8524    match decorations {
 8525        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 8526        Decorations::Server => window.set_client_inset(px(0.0)),
 8527    }
 8528
 8529    struct GlobalResizeEdge(ResizeEdge);
 8530    impl Global for GlobalResizeEdge {}
 8531
 8532    div()
 8533        .id("window-backdrop")
 8534        .bg(transparent_black())
 8535        .map(|div| match decorations {
 8536            Decorations::Server => div,
 8537            Decorations::Client { tiling, .. } => div
 8538                .when(!(tiling.top || tiling.right), |div| {
 8539                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8540                })
 8541                .when(!(tiling.top || tiling.left), |div| {
 8542                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8543                })
 8544                .when(!(tiling.bottom || tiling.right), |div| {
 8545                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8546                })
 8547                .when(!(tiling.bottom || tiling.left), |div| {
 8548                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8549                })
 8550                .when(!tiling.top, |div| {
 8551                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8552                })
 8553                .when(!tiling.bottom, |div| {
 8554                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8555                })
 8556                .when(!tiling.left, |div| {
 8557                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8558                })
 8559                .when(!tiling.right, |div| {
 8560                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8561                })
 8562                .on_mouse_move(move |e, window, cx| {
 8563                    let size = window.window_bounds().get_bounds().size;
 8564                    let pos = e.position;
 8565
 8566                    let new_edge =
 8567                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8568
 8569                    let edge = cx.try_global::<GlobalResizeEdge>();
 8570                    if new_edge != edge.map(|edge| edge.0) {
 8571                        window
 8572                            .window_handle()
 8573                            .update(cx, |workspace, _, cx| {
 8574                                cx.notify(workspace.entity_id());
 8575                            })
 8576                            .ok();
 8577                    }
 8578                })
 8579                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8580                    let size = window.window_bounds().get_bounds().size;
 8581                    let pos = e.position;
 8582
 8583                    let edge = match resize_edge(
 8584                        pos,
 8585                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8586                        size,
 8587                        tiling,
 8588                    ) {
 8589                        Some(value) => value,
 8590                        None => return,
 8591                    };
 8592
 8593                    window.start_window_resize(edge);
 8594                }),
 8595        })
 8596        .size_full()
 8597        .child(
 8598            div()
 8599                .cursor(CursorStyle::Arrow)
 8600                .map(|div| match decorations {
 8601                    Decorations::Server => div,
 8602                    Decorations::Client { tiling } => div
 8603                        .border_color(cx.theme().colors().border)
 8604                        .when(!(tiling.top || tiling.right), |div| {
 8605                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8606                        })
 8607                        .when(!(tiling.top || tiling.left), |div| {
 8608                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8609                        })
 8610                        .when(!(tiling.bottom || tiling.right), |div| {
 8611                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8612                        })
 8613                        .when(!(tiling.bottom || tiling.left), |div| {
 8614                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8615                        })
 8616                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8617                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8618                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8619                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8620                        .when(!tiling.is_tiled(), |div| {
 8621                            div.shadow(vec![gpui::BoxShadow {
 8622                                color: Hsla {
 8623                                    h: 0.,
 8624                                    s: 0.,
 8625                                    l: 0.,
 8626                                    a: 0.4,
 8627                                },
 8628                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8629                                spread_radius: px(0.),
 8630                                offset: point(px(0.0), px(0.0)),
 8631                            }])
 8632                        }),
 8633                })
 8634                .on_mouse_move(|_e, _, cx| {
 8635                    cx.stop_propagation();
 8636                })
 8637                .size_full()
 8638                .child(element),
 8639        )
 8640        .map(|div| match decorations {
 8641            Decorations::Server => div,
 8642            Decorations::Client { tiling, .. } => div.child(
 8643                canvas(
 8644                    |_bounds, window, _| {
 8645                        window.insert_hitbox(
 8646                            Bounds::new(
 8647                                point(px(0.0), px(0.0)),
 8648                                window.window_bounds().get_bounds().size,
 8649                            ),
 8650                            HitboxBehavior::Normal,
 8651                        )
 8652                    },
 8653                    move |_bounds, hitbox, window, cx| {
 8654                        let mouse = window.mouse_position();
 8655                        let size = window.window_bounds().get_bounds().size;
 8656                        let Some(edge) =
 8657                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8658                        else {
 8659                            return;
 8660                        };
 8661                        cx.set_global(GlobalResizeEdge(edge));
 8662                        window.set_cursor_style(
 8663                            match edge {
 8664                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8665                                ResizeEdge::Left | ResizeEdge::Right => {
 8666                                    CursorStyle::ResizeLeftRight
 8667                                }
 8668                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8669                                    CursorStyle::ResizeUpLeftDownRight
 8670                                }
 8671                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8672                                    CursorStyle::ResizeUpRightDownLeft
 8673                                }
 8674                            },
 8675                            &hitbox,
 8676                        );
 8677                    },
 8678                )
 8679                .size_full()
 8680                .absolute(),
 8681            ),
 8682        })
 8683}
 8684
 8685fn resize_edge(
 8686    pos: Point<Pixels>,
 8687    shadow_size: Pixels,
 8688    window_size: Size<Pixels>,
 8689    tiling: Tiling,
 8690) -> Option<ResizeEdge> {
 8691    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8692    if bounds.contains(&pos) {
 8693        return None;
 8694    }
 8695
 8696    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8697    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8698    if !tiling.top && top_left_bounds.contains(&pos) {
 8699        return Some(ResizeEdge::TopLeft);
 8700    }
 8701
 8702    let top_right_bounds = Bounds::new(
 8703        Point::new(window_size.width - corner_size.width, px(0.)),
 8704        corner_size,
 8705    );
 8706    if !tiling.top && top_right_bounds.contains(&pos) {
 8707        return Some(ResizeEdge::TopRight);
 8708    }
 8709
 8710    let bottom_left_bounds = Bounds::new(
 8711        Point::new(px(0.), window_size.height - corner_size.height),
 8712        corner_size,
 8713    );
 8714    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8715        return Some(ResizeEdge::BottomLeft);
 8716    }
 8717
 8718    let bottom_right_bounds = Bounds::new(
 8719        Point::new(
 8720            window_size.width - corner_size.width,
 8721            window_size.height - corner_size.height,
 8722        ),
 8723        corner_size,
 8724    );
 8725    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8726        return Some(ResizeEdge::BottomRight);
 8727    }
 8728
 8729    if !tiling.top && pos.y < shadow_size {
 8730        Some(ResizeEdge::Top)
 8731    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8732        Some(ResizeEdge::Bottom)
 8733    } else if !tiling.left && pos.x < shadow_size {
 8734        Some(ResizeEdge::Left)
 8735    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8736        Some(ResizeEdge::Right)
 8737    } else {
 8738        None
 8739    }
 8740}
 8741
 8742fn join_pane_into_active(
 8743    active_pane: &Entity<Pane>,
 8744    pane: &Entity<Pane>,
 8745    window: &mut Window,
 8746    cx: &mut App,
 8747) {
 8748    if pane == active_pane {
 8749    } else if pane.read(cx).items_len() == 0 {
 8750        pane.update(cx, |_, cx| {
 8751            cx.emit(pane::Event::Remove {
 8752                focus_on_pane: None,
 8753            });
 8754        })
 8755    } else {
 8756        move_all_items(pane, active_pane, window, cx);
 8757    }
 8758}
 8759
 8760fn move_all_items(
 8761    from_pane: &Entity<Pane>,
 8762    to_pane: &Entity<Pane>,
 8763    window: &mut Window,
 8764    cx: &mut App,
 8765) {
 8766    let destination_is_different = from_pane != to_pane;
 8767    let mut moved_items = 0;
 8768    for (item_ix, item_handle) in from_pane
 8769        .read(cx)
 8770        .items()
 8771        .enumerate()
 8772        .map(|(ix, item)| (ix, item.clone()))
 8773        .collect::<Vec<_>>()
 8774    {
 8775        let ix = item_ix - moved_items;
 8776        if destination_is_different {
 8777            // Close item from previous pane
 8778            from_pane.update(cx, |source, cx| {
 8779                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8780            });
 8781            moved_items += 1;
 8782        }
 8783
 8784        // This automatically removes duplicate items in the pane
 8785        to_pane.update(cx, |destination, cx| {
 8786            destination.add_item(item_handle, true, true, None, window, cx);
 8787            window.focus(&destination.focus_handle(cx), cx)
 8788        });
 8789    }
 8790}
 8791
 8792pub fn move_item(
 8793    source: &Entity<Pane>,
 8794    destination: &Entity<Pane>,
 8795    item_id_to_move: EntityId,
 8796    destination_index: usize,
 8797    activate: bool,
 8798    window: &mut Window,
 8799    cx: &mut App,
 8800) {
 8801    let Some((item_ix, item_handle)) = source
 8802        .read(cx)
 8803        .items()
 8804        .enumerate()
 8805        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8806        .map(|(ix, item)| (ix, item.clone()))
 8807    else {
 8808        // Tab was closed during drag
 8809        return;
 8810    };
 8811
 8812    if source != destination {
 8813        // Close item from previous pane
 8814        source.update(cx, |source, cx| {
 8815            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8816        });
 8817    }
 8818
 8819    // This automatically removes duplicate items in the pane
 8820    destination.update(cx, |destination, cx| {
 8821        destination.add_item_inner(
 8822            item_handle,
 8823            activate,
 8824            activate,
 8825            activate,
 8826            Some(destination_index),
 8827            window,
 8828            cx,
 8829        );
 8830        if activate {
 8831            window.focus(&destination.focus_handle(cx), cx)
 8832        }
 8833    });
 8834}
 8835
 8836pub fn move_active_item(
 8837    source: &Entity<Pane>,
 8838    destination: &Entity<Pane>,
 8839    focus_destination: bool,
 8840    close_if_empty: bool,
 8841    window: &mut Window,
 8842    cx: &mut App,
 8843) {
 8844    if source == destination {
 8845        return;
 8846    }
 8847    let Some(active_item) = source.read(cx).active_item() else {
 8848        return;
 8849    };
 8850    source.update(cx, |source_pane, cx| {
 8851        let item_id = active_item.item_id();
 8852        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8853        destination.update(cx, |target_pane, cx| {
 8854            target_pane.add_item(
 8855                active_item,
 8856                focus_destination,
 8857                focus_destination,
 8858                Some(target_pane.items_len()),
 8859                window,
 8860                cx,
 8861            );
 8862        });
 8863    });
 8864}
 8865
 8866pub fn clone_active_item(
 8867    workspace_id: Option<WorkspaceId>,
 8868    source: &Entity<Pane>,
 8869    destination: &Entity<Pane>,
 8870    focus_destination: bool,
 8871    window: &mut Window,
 8872    cx: &mut App,
 8873) {
 8874    if source == destination {
 8875        return;
 8876    }
 8877    let Some(active_item) = source.read(cx).active_item() else {
 8878        return;
 8879    };
 8880    if !active_item.can_split(cx) {
 8881        return;
 8882    }
 8883    let destination = destination.downgrade();
 8884    let task = active_item.clone_on_split(workspace_id, window, cx);
 8885    window
 8886        .spawn(cx, async move |cx| {
 8887            let Some(clone) = task.await else {
 8888                return;
 8889            };
 8890            destination
 8891                .update_in(cx, |target_pane, window, cx| {
 8892                    target_pane.add_item(
 8893                        clone,
 8894                        focus_destination,
 8895                        focus_destination,
 8896                        Some(target_pane.items_len()),
 8897                        window,
 8898                        cx,
 8899                    );
 8900                })
 8901                .log_err();
 8902        })
 8903        .detach();
 8904}
 8905
 8906#[derive(Debug)]
 8907pub struct WorkspacePosition {
 8908    pub window_bounds: Option<WindowBounds>,
 8909    pub display: Option<Uuid>,
 8910    pub centered_layout: bool,
 8911}
 8912
 8913pub fn remote_workspace_position_from_db(
 8914    connection_options: RemoteConnectionOptions,
 8915    paths_to_open: &[PathBuf],
 8916    cx: &App,
 8917) -> Task<Result<WorkspacePosition>> {
 8918    let paths = paths_to_open.to_vec();
 8919
 8920    cx.background_spawn(async move {
 8921        let remote_connection_id = persistence::DB
 8922            .get_or_create_remote_connection(connection_options)
 8923            .await
 8924            .context("fetching serialized ssh project")?;
 8925        let serialized_workspace =
 8926            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8927
 8928        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8929            (Some(WindowBounds::Windowed(bounds)), None)
 8930        } else {
 8931            let restorable_bounds = serialized_workspace
 8932                .as_ref()
 8933                .and_then(|workspace| {
 8934                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 8935                })
 8936                .or_else(|| persistence::read_default_window_bounds());
 8937
 8938            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 8939                (Some(serialized_bounds), Some(serialized_display))
 8940            } else {
 8941                (None, None)
 8942            }
 8943        };
 8944
 8945        let centered_layout = serialized_workspace
 8946            .as_ref()
 8947            .map(|w| w.centered_layout)
 8948            .unwrap_or(false);
 8949
 8950        Ok(WorkspacePosition {
 8951            window_bounds,
 8952            display,
 8953            centered_layout,
 8954        })
 8955    })
 8956}
 8957
 8958pub fn with_active_or_new_workspace(
 8959    cx: &mut App,
 8960    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8961) {
 8962    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8963        Some(workspace) => {
 8964            cx.defer(move |cx| {
 8965                workspace
 8966                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8967                    .log_err();
 8968            });
 8969        }
 8970        None => {
 8971            let app_state = AppState::global(cx);
 8972            if let Some(app_state) = app_state.upgrade() {
 8973                open_new(
 8974                    OpenOptions::default(),
 8975                    app_state,
 8976                    cx,
 8977                    move |workspace, window, cx| f(workspace, window, cx),
 8978                )
 8979                .detach_and_log_err(cx);
 8980            }
 8981        }
 8982    }
 8983}
 8984
 8985#[cfg(test)]
 8986mod tests {
 8987    use std::{cell::RefCell, rc::Rc};
 8988
 8989    use super::*;
 8990    use crate::{
 8991        dock::{PanelEvent, test::TestPanel},
 8992        item::{
 8993            ItemBufferKind, ItemEvent,
 8994            test::{TestItem, TestProjectItem},
 8995        },
 8996    };
 8997    use fs::FakeFs;
 8998    use gpui::{
 8999        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9000        UpdateGlobal, VisualTestContext, px,
 9001    };
 9002    use project::{Project, ProjectEntryId};
 9003    use serde_json::json;
 9004    use settings::SettingsStore;
 9005    use util::rel_path::rel_path;
 9006
 9007    #[gpui::test]
 9008    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9009        init_test(cx);
 9010
 9011        let fs = FakeFs::new(cx.executor());
 9012        let project = Project::test(fs, [], cx).await;
 9013        let (workspace, cx) =
 9014            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9015
 9016        // Adding an item with no ambiguity renders the tab without detail.
 9017        let item1 = cx.new(|cx| {
 9018            let mut item = TestItem::new(cx);
 9019            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9020            item
 9021        });
 9022        workspace.update_in(cx, |workspace, window, cx| {
 9023            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9024        });
 9025        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9026
 9027        // Adding an item that creates ambiguity increases the level of detail on
 9028        // both tabs.
 9029        let item2 = cx.new_window_entity(|_window, cx| {
 9030            let mut item = TestItem::new(cx);
 9031            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9032            item
 9033        });
 9034        workspace.update_in(cx, |workspace, window, cx| {
 9035            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9036        });
 9037        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9038        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9039
 9040        // Adding an item that creates ambiguity increases the level of detail only
 9041        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9042        // we stop at the highest detail available.
 9043        let item3 = cx.new(|cx| {
 9044            let mut item = TestItem::new(cx);
 9045            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9046            item
 9047        });
 9048        workspace.update_in(cx, |workspace, window, cx| {
 9049            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9050        });
 9051        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9052        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9053        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9054    }
 9055
 9056    #[gpui::test]
 9057    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9058        init_test(cx);
 9059
 9060        let fs = FakeFs::new(cx.executor());
 9061        fs.insert_tree(
 9062            "/root1",
 9063            json!({
 9064                "one.txt": "",
 9065                "two.txt": "",
 9066            }),
 9067        )
 9068        .await;
 9069        fs.insert_tree(
 9070            "/root2",
 9071            json!({
 9072                "three.txt": "",
 9073            }),
 9074        )
 9075        .await;
 9076
 9077        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9078        let (workspace, cx) =
 9079            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9080        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9081        let worktree_id = project.update(cx, |project, cx| {
 9082            project.worktrees(cx).next().unwrap().read(cx).id()
 9083        });
 9084
 9085        let item1 = cx.new(|cx| {
 9086            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9087        });
 9088        let item2 = cx.new(|cx| {
 9089            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9090        });
 9091
 9092        // Add an item to an empty pane
 9093        workspace.update_in(cx, |workspace, window, cx| {
 9094            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9095        });
 9096        project.update(cx, |project, cx| {
 9097            assert_eq!(
 9098                project.active_entry(),
 9099                project
 9100                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9101                    .map(|e| e.id)
 9102            );
 9103        });
 9104        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9105
 9106        // Add a second item to a non-empty pane
 9107        workspace.update_in(cx, |workspace, window, cx| {
 9108            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9109        });
 9110        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9111        project.update(cx, |project, cx| {
 9112            assert_eq!(
 9113                project.active_entry(),
 9114                project
 9115                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9116                    .map(|e| e.id)
 9117            );
 9118        });
 9119
 9120        // Close the active item
 9121        pane.update_in(cx, |pane, window, cx| {
 9122            pane.close_active_item(&Default::default(), window, cx)
 9123        })
 9124        .await
 9125        .unwrap();
 9126        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9127        project.update(cx, |project, cx| {
 9128            assert_eq!(
 9129                project.active_entry(),
 9130                project
 9131                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9132                    .map(|e| e.id)
 9133            );
 9134        });
 9135
 9136        // Add a project folder
 9137        project
 9138            .update(cx, |project, cx| {
 9139                project.find_or_create_worktree("root2", true, cx)
 9140            })
 9141            .await
 9142            .unwrap();
 9143        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 9144
 9145        // Remove a project folder
 9146        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 9147        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 9148    }
 9149
 9150    #[gpui::test]
 9151    async fn test_close_window(cx: &mut TestAppContext) {
 9152        init_test(cx);
 9153
 9154        let fs = FakeFs::new(cx.executor());
 9155        fs.insert_tree("/root", json!({ "one": "" })).await;
 9156
 9157        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9158        let (workspace, cx) =
 9159            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9160
 9161        // When there are no dirty items, there's nothing to do.
 9162        let item1 = cx.new(TestItem::new);
 9163        workspace.update_in(cx, |w, window, cx| {
 9164            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 9165        });
 9166        let task = workspace.update_in(cx, |w, window, cx| {
 9167            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9168        });
 9169        assert!(task.await.unwrap());
 9170
 9171        // When there are dirty untitled items, prompt to save each one. If the user
 9172        // cancels any prompt, then abort.
 9173        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 9174        let item3 = cx.new(|cx| {
 9175            TestItem::new(cx)
 9176                .with_dirty(true)
 9177                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9178        });
 9179        workspace.update_in(cx, |w, window, cx| {
 9180            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9181            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9182        });
 9183        let task = workspace.update_in(cx, |w, window, cx| {
 9184            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9185        });
 9186        cx.executor().run_until_parked();
 9187        cx.simulate_prompt_answer("Cancel"); // cancel save all
 9188        cx.executor().run_until_parked();
 9189        assert!(!cx.has_pending_prompt());
 9190        assert!(!task.await.unwrap());
 9191    }
 9192
 9193    #[gpui::test]
 9194    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 9195        init_test(cx);
 9196
 9197        // Register TestItem as a serializable item
 9198        cx.update(|cx| {
 9199            register_serializable_item::<TestItem>(cx);
 9200        });
 9201
 9202        let fs = FakeFs::new(cx.executor());
 9203        fs.insert_tree("/root", json!({ "one": "" })).await;
 9204
 9205        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9206        let (workspace, cx) =
 9207            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9208
 9209        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 9210        let item1 = cx.new(|cx| {
 9211            TestItem::new(cx)
 9212                .with_dirty(true)
 9213                .with_serialize(|| Some(Task::ready(Ok(()))))
 9214        });
 9215        let item2 = cx.new(|cx| {
 9216            TestItem::new(cx)
 9217                .with_dirty(true)
 9218                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9219                .with_serialize(|| Some(Task::ready(Ok(()))))
 9220        });
 9221        workspace.update_in(cx, |w, window, cx| {
 9222            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9223            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9224        });
 9225        let task = workspace.update_in(cx, |w, window, cx| {
 9226            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9227        });
 9228        assert!(task.await.unwrap());
 9229    }
 9230
 9231    #[gpui::test]
 9232    async fn test_close_pane_items(cx: &mut TestAppContext) {
 9233        init_test(cx);
 9234
 9235        let fs = FakeFs::new(cx.executor());
 9236
 9237        let project = Project::test(fs, None, cx).await;
 9238        let (workspace, cx) =
 9239            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9240
 9241        let item1 = cx.new(|cx| {
 9242            TestItem::new(cx)
 9243                .with_dirty(true)
 9244                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9245        });
 9246        let item2 = cx.new(|cx| {
 9247            TestItem::new(cx)
 9248                .with_dirty(true)
 9249                .with_conflict(true)
 9250                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9251        });
 9252        let item3 = cx.new(|cx| {
 9253            TestItem::new(cx)
 9254                .with_dirty(true)
 9255                .with_conflict(true)
 9256                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 9257        });
 9258        let item4 = cx.new(|cx| {
 9259            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 9260                let project_item = TestProjectItem::new_untitled(cx);
 9261                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9262                project_item
 9263            }])
 9264        });
 9265        let pane = workspace.update_in(cx, |workspace, window, cx| {
 9266            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9267            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9268            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9269            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 9270            workspace.active_pane().clone()
 9271        });
 9272
 9273        let close_items = pane.update_in(cx, |pane, window, cx| {
 9274            pane.activate_item(1, true, true, window, cx);
 9275            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9276            let item1_id = item1.item_id();
 9277            let item3_id = item3.item_id();
 9278            let item4_id = item4.item_id();
 9279            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 9280                [item1_id, item3_id, item4_id].contains(&id)
 9281            })
 9282        });
 9283        cx.executor().run_until_parked();
 9284
 9285        assert!(cx.has_pending_prompt());
 9286        cx.simulate_prompt_answer("Save all");
 9287
 9288        cx.executor().run_until_parked();
 9289
 9290        // Item 1 is saved. There's a prompt to save item 3.
 9291        pane.update(cx, |pane, cx| {
 9292            assert_eq!(item1.read(cx).save_count, 1);
 9293            assert_eq!(item1.read(cx).save_as_count, 0);
 9294            assert_eq!(item1.read(cx).reload_count, 0);
 9295            assert_eq!(pane.items_len(), 3);
 9296            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 9297        });
 9298        assert!(cx.has_pending_prompt());
 9299
 9300        // Cancel saving item 3.
 9301        cx.simulate_prompt_answer("Discard");
 9302        cx.executor().run_until_parked();
 9303
 9304        // Item 3 is reloaded. There's a prompt to save item 4.
 9305        pane.update(cx, |pane, cx| {
 9306            assert_eq!(item3.read(cx).save_count, 0);
 9307            assert_eq!(item3.read(cx).save_as_count, 0);
 9308            assert_eq!(item3.read(cx).reload_count, 1);
 9309            assert_eq!(pane.items_len(), 2);
 9310            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 9311        });
 9312
 9313        // There's a prompt for a path for item 4.
 9314        cx.simulate_new_path_selection(|_| Some(Default::default()));
 9315        close_items.await.unwrap();
 9316
 9317        // The requested items are closed.
 9318        pane.update(cx, |pane, cx| {
 9319            assert_eq!(item4.read(cx).save_count, 0);
 9320            assert_eq!(item4.read(cx).save_as_count, 1);
 9321            assert_eq!(item4.read(cx).reload_count, 0);
 9322            assert_eq!(pane.items_len(), 1);
 9323            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9324        });
 9325    }
 9326
 9327    #[gpui::test]
 9328    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 9329        init_test(cx);
 9330
 9331        let fs = FakeFs::new(cx.executor());
 9332        let project = Project::test(fs, [], cx).await;
 9333        let (workspace, cx) =
 9334            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9335
 9336        // Create several workspace items with single project entries, and two
 9337        // workspace items with multiple project entries.
 9338        let single_entry_items = (0..=4)
 9339            .map(|project_entry_id| {
 9340                cx.new(|cx| {
 9341                    TestItem::new(cx)
 9342                        .with_dirty(true)
 9343                        .with_project_items(&[dirty_project_item(
 9344                            project_entry_id,
 9345                            &format!("{project_entry_id}.txt"),
 9346                            cx,
 9347                        )])
 9348                })
 9349            })
 9350            .collect::<Vec<_>>();
 9351        let item_2_3 = cx.new(|cx| {
 9352            TestItem::new(cx)
 9353                .with_dirty(true)
 9354                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9355                .with_project_items(&[
 9356                    single_entry_items[2].read(cx).project_items[0].clone(),
 9357                    single_entry_items[3].read(cx).project_items[0].clone(),
 9358                ])
 9359        });
 9360        let item_3_4 = cx.new(|cx| {
 9361            TestItem::new(cx)
 9362                .with_dirty(true)
 9363                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9364                .with_project_items(&[
 9365                    single_entry_items[3].read(cx).project_items[0].clone(),
 9366                    single_entry_items[4].read(cx).project_items[0].clone(),
 9367                ])
 9368        });
 9369
 9370        // Create two panes that contain the following project entries:
 9371        //   left pane:
 9372        //     multi-entry items:   (2, 3)
 9373        //     single-entry items:  0, 2, 3, 4
 9374        //   right pane:
 9375        //     single-entry items:  4, 1
 9376        //     multi-entry items:   (3, 4)
 9377        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 9378            let left_pane = workspace.active_pane().clone();
 9379            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 9380            workspace.add_item_to_active_pane(
 9381                single_entry_items[0].boxed_clone(),
 9382                None,
 9383                true,
 9384                window,
 9385                cx,
 9386            );
 9387            workspace.add_item_to_active_pane(
 9388                single_entry_items[2].boxed_clone(),
 9389                None,
 9390                true,
 9391                window,
 9392                cx,
 9393            );
 9394            workspace.add_item_to_active_pane(
 9395                single_entry_items[3].boxed_clone(),
 9396                None,
 9397                true,
 9398                window,
 9399                cx,
 9400            );
 9401            workspace.add_item_to_active_pane(
 9402                single_entry_items[4].boxed_clone(),
 9403                None,
 9404                true,
 9405                window,
 9406                cx,
 9407            );
 9408
 9409            let right_pane =
 9410                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 9411
 9412            let boxed_clone = single_entry_items[1].boxed_clone();
 9413            let right_pane = window.spawn(cx, async move |cx| {
 9414                right_pane.await.inspect(|right_pane| {
 9415                    right_pane
 9416                        .update_in(cx, |pane, window, cx| {
 9417                            pane.add_item(boxed_clone, true, true, None, window, cx);
 9418                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 9419                        })
 9420                        .unwrap();
 9421                })
 9422            });
 9423
 9424            (left_pane, right_pane)
 9425        });
 9426        let right_pane = right_pane.await.unwrap();
 9427        cx.focus(&right_pane);
 9428
 9429        let close = right_pane.update_in(cx, |pane, window, cx| {
 9430            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9431                .unwrap()
 9432        });
 9433        cx.executor().run_until_parked();
 9434
 9435        let msg = cx.pending_prompt().unwrap().0;
 9436        assert!(msg.contains("1.txt"));
 9437        assert!(!msg.contains("2.txt"));
 9438        assert!(!msg.contains("3.txt"));
 9439        assert!(!msg.contains("4.txt"));
 9440
 9441        // With best-effort close, cancelling item 1 keeps it open but items 4
 9442        // and (3,4) still close since their entries exist in left pane.
 9443        cx.simulate_prompt_answer("Cancel");
 9444        close.await;
 9445
 9446        right_pane.read_with(cx, |pane, _| {
 9447            assert_eq!(pane.items_len(), 1);
 9448        });
 9449
 9450        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
 9451        left_pane
 9452            .update_in(cx, |left_pane, window, cx| {
 9453                left_pane.close_item_by_id(
 9454                    single_entry_items[3].entity_id(),
 9455                    SaveIntent::Skip,
 9456                    window,
 9457                    cx,
 9458                )
 9459            })
 9460            .await
 9461            .unwrap();
 9462
 9463        let close = left_pane.update_in(cx, |pane, window, cx| {
 9464            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9465                .unwrap()
 9466        });
 9467        cx.executor().run_until_parked();
 9468
 9469        let details = cx.pending_prompt().unwrap().1;
 9470        assert!(details.contains("0.txt"));
 9471        assert!(details.contains("3.txt"));
 9472        assert!(details.contains("4.txt"));
 9473        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
 9474        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
 9475        // assert!(!details.contains("2.txt"));
 9476
 9477        cx.simulate_prompt_answer("Save all");
 9478        cx.executor().run_until_parked();
 9479        close.await;
 9480
 9481        left_pane.read_with(cx, |pane, _| {
 9482            assert_eq!(pane.items_len(), 0);
 9483        });
 9484    }
 9485
 9486    #[gpui::test]
 9487    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 9488        init_test(cx);
 9489
 9490        let fs = FakeFs::new(cx.executor());
 9491        let project = Project::test(fs, [], cx).await;
 9492        let (workspace, cx) =
 9493            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9494        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9495
 9496        let item = cx.new(|cx| {
 9497            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9498        });
 9499        let item_id = item.entity_id();
 9500        workspace.update_in(cx, |workspace, window, cx| {
 9501            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9502        });
 9503
 9504        // Autosave on window change.
 9505        item.update(cx, |item, cx| {
 9506            SettingsStore::update_global(cx, |settings, cx| {
 9507                settings.update_user_settings(cx, |settings| {
 9508                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 9509                })
 9510            });
 9511            item.is_dirty = true;
 9512        });
 9513
 9514        // Deactivating the window saves the file.
 9515        cx.deactivate_window();
 9516        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9517
 9518        // Re-activating the window doesn't save the file.
 9519        cx.update(|window, _| window.activate_window());
 9520        cx.executor().run_until_parked();
 9521        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9522
 9523        // Autosave on focus change.
 9524        item.update_in(cx, |item, window, cx| {
 9525            cx.focus_self(window);
 9526            SettingsStore::update_global(cx, |settings, cx| {
 9527                settings.update_user_settings(cx, |settings| {
 9528                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9529                })
 9530            });
 9531            item.is_dirty = true;
 9532        });
 9533        // Blurring the item saves the file.
 9534        item.update_in(cx, |_, window, _| window.blur());
 9535        cx.executor().run_until_parked();
 9536        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 9537
 9538        // Deactivating the window still saves the file.
 9539        item.update_in(cx, |item, window, cx| {
 9540            cx.focus_self(window);
 9541            item.is_dirty = true;
 9542        });
 9543        cx.deactivate_window();
 9544        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 9545
 9546        // Autosave after delay.
 9547        item.update(cx, |item, cx| {
 9548            SettingsStore::update_global(cx, |settings, cx| {
 9549                settings.update_user_settings(cx, |settings| {
 9550                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 9551                        milliseconds: 500.into(),
 9552                    });
 9553                })
 9554            });
 9555            item.is_dirty = true;
 9556            cx.emit(ItemEvent::Edit);
 9557        });
 9558
 9559        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 9560        cx.executor().advance_clock(Duration::from_millis(250));
 9561        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 9562
 9563        // After delay expires, the file is saved.
 9564        cx.executor().advance_clock(Duration::from_millis(250));
 9565        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9566
 9567        // Autosave after delay, should save earlier than delay if tab is closed
 9568        item.update(cx, |item, cx| {
 9569            item.is_dirty = true;
 9570            cx.emit(ItemEvent::Edit);
 9571        });
 9572        cx.executor().advance_clock(Duration::from_millis(250));
 9573        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9574
 9575        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9576        pane.update_in(cx, |pane, window, cx| {
 9577            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9578        })
 9579        .await
 9580        .unwrap();
 9581        assert!(!cx.has_pending_prompt());
 9582        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9583
 9584        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9585        workspace.update_in(cx, |workspace, window, cx| {
 9586            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9587        });
 9588        item.update_in(cx, |item, _window, cx| {
 9589            item.is_dirty = true;
 9590            for project_item in &mut item.project_items {
 9591                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9592            }
 9593        });
 9594        cx.run_until_parked();
 9595        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9596
 9597        // Autosave on focus change, ensuring closing the tab counts as such.
 9598        item.update(cx, |item, cx| {
 9599            SettingsStore::update_global(cx, |settings, cx| {
 9600                settings.update_user_settings(cx, |settings| {
 9601                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9602                })
 9603            });
 9604            item.is_dirty = true;
 9605            for project_item in &mut item.project_items {
 9606                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9607            }
 9608        });
 9609
 9610        pane.update_in(cx, |pane, window, cx| {
 9611            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9612        })
 9613        .await
 9614        .unwrap();
 9615        assert!(!cx.has_pending_prompt());
 9616        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9617
 9618        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9619        workspace.update_in(cx, |workspace, window, cx| {
 9620            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9621        });
 9622        item.update_in(cx, |item, window, cx| {
 9623            item.project_items[0].update(cx, |item, _| {
 9624                item.entry_id = None;
 9625            });
 9626            item.is_dirty = true;
 9627            window.blur();
 9628        });
 9629        cx.run_until_parked();
 9630        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9631
 9632        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9633        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9634            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9635        });
 9636        cx.run_until_parked();
 9637        assert!(cx.has_pending_prompt());
 9638        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9639    }
 9640
 9641    #[gpui::test]
 9642    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9643        init_test(cx);
 9644
 9645        let fs = FakeFs::new(cx.executor());
 9646
 9647        let project = Project::test(fs, [], cx).await;
 9648        let (workspace, cx) =
 9649            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9650
 9651        let item = cx.new(|cx| {
 9652            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9653        });
 9654        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9655        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9656        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9657
 9658        workspace.update_in(cx, |workspace, window, cx| {
 9659            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9660            let toolbar_notification_count = toolbar_notify_count.clone();
 9661            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9662                *toolbar_notification_count.borrow_mut() += 1
 9663            })
 9664            .detach();
 9665        });
 9666
 9667        pane.read_with(cx, |pane, _| {
 9668            assert!(!pane.can_navigate_backward());
 9669            assert!(!pane.can_navigate_forward());
 9670        });
 9671
 9672        item.update_in(cx, |item, _, cx| {
 9673            item.set_state("one".to_string(), cx);
 9674        });
 9675
 9676        // Toolbar must be notified to re-render the navigation buttons
 9677        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9678
 9679        pane.read_with(cx, |pane, _| {
 9680            assert!(pane.can_navigate_backward());
 9681            assert!(!pane.can_navigate_forward());
 9682        });
 9683
 9684        workspace
 9685            .update_in(cx, |workspace, window, cx| {
 9686                workspace.go_back(pane.downgrade(), window, cx)
 9687            })
 9688            .await
 9689            .unwrap();
 9690
 9691        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9692        pane.read_with(cx, |pane, _| {
 9693            assert!(!pane.can_navigate_backward());
 9694            assert!(pane.can_navigate_forward());
 9695        });
 9696    }
 9697
 9698    #[gpui::test]
 9699    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9700        init_test(cx);
 9701        let fs = FakeFs::new(cx.executor());
 9702
 9703        let project = Project::test(fs, [], cx).await;
 9704        let (workspace, cx) =
 9705            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9706
 9707        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9708            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
 9709            workspace.add_panel(panel.clone(), window, cx);
 9710
 9711            workspace
 9712                .right_dock()
 9713                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9714
 9715            panel
 9716        });
 9717
 9718        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9719        pane.update_in(cx, |pane, window, cx| {
 9720            let item = cx.new(TestItem::new);
 9721            pane.add_item(Box::new(item), true, true, None, window, cx);
 9722        });
 9723
 9724        // Transfer focus from center to panel
 9725        workspace.update_in(cx, |workspace, window, cx| {
 9726            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9727        });
 9728
 9729        workspace.update_in(cx, |workspace, window, cx| {
 9730            assert!(workspace.right_dock().read(cx).is_open());
 9731            assert!(!panel.is_zoomed(window, cx));
 9732            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9733        });
 9734
 9735        // Transfer focus from panel to center
 9736        workspace.update_in(cx, |workspace, window, cx| {
 9737            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9738        });
 9739
 9740        workspace.update_in(cx, |workspace, window, cx| {
 9741            assert!(workspace.right_dock().read(cx).is_open());
 9742            assert!(!panel.is_zoomed(window, cx));
 9743            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9744        });
 9745
 9746        // Close the dock
 9747        workspace.update_in(cx, |workspace, window, cx| {
 9748            workspace.toggle_dock(DockPosition::Right, window, cx);
 9749        });
 9750
 9751        workspace.update_in(cx, |workspace, window, cx| {
 9752            assert!(!workspace.right_dock().read(cx).is_open());
 9753            assert!(!panel.is_zoomed(window, cx));
 9754            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9755        });
 9756
 9757        // Open the dock
 9758        workspace.update_in(cx, |workspace, window, cx| {
 9759            workspace.toggle_dock(DockPosition::Right, window, cx);
 9760        });
 9761
 9762        workspace.update_in(cx, |workspace, window, cx| {
 9763            assert!(workspace.right_dock().read(cx).is_open());
 9764            assert!(!panel.is_zoomed(window, cx));
 9765            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9766        });
 9767
 9768        // Focus and zoom panel
 9769        panel.update_in(cx, |panel, window, cx| {
 9770            cx.focus_self(window);
 9771            panel.set_zoomed(true, window, cx)
 9772        });
 9773
 9774        workspace.update_in(cx, |workspace, window, cx| {
 9775            assert!(workspace.right_dock().read(cx).is_open());
 9776            assert!(panel.is_zoomed(window, cx));
 9777            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9778        });
 9779
 9780        // Transfer focus to the center closes the dock
 9781        workspace.update_in(cx, |workspace, window, cx| {
 9782            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9783        });
 9784
 9785        workspace.update_in(cx, |workspace, window, cx| {
 9786            assert!(!workspace.right_dock().read(cx).is_open());
 9787            assert!(panel.is_zoomed(window, cx));
 9788            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9789        });
 9790
 9791        // Transferring focus back to the panel keeps it zoomed
 9792        workspace.update_in(cx, |workspace, window, cx| {
 9793            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9794        });
 9795
 9796        workspace.update_in(cx, |workspace, window, cx| {
 9797            assert!(workspace.right_dock().read(cx).is_open());
 9798            assert!(panel.is_zoomed(window, cx));
 9799            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9800        });
 9801
 9802        // Close the dock while it is zoomed
 9803        workspace.update_in(cx, |workspace, window, cx| {
 9804            workspace.toggle_dock(DockPosition::Right, window, cx)
 9805        });
 9806
 9807        workspace.update_in(cx, |workspace, window, cx| {
 9808            assert!(!workspace.right_dock().read(cx).is_open());
 9809            assert!(panel.is_zoomed(window, cx));
 9810            assert!(workspace.zoomed.is_none());
 9811            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9812        });
 9813
 9814        // Opening the dock, when it's zoomed, retains focus
 9815        workspace.update_in(cx, |workspace, window, cx| {
 9816            workspace.toggle_dock(DockPosition::Right, window, cx)
 9817        });
 9818
 9819        workspace.update_in(cx, |workspace, window, cx| {
 9820            assert!(workspace.right_dock().read(cx).is_open());
 9821            assert!(panel.is_zoomed(window, cx));
 9822            assert!(workspace.zoomed.is_some());
 9823            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9824        });
 9825
 9826        // Unzoom and close the panel, zoom the active pane.
 9827        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9828        workspace.update_in(cx, |workspace, window, cx| {
 9829            workspace.toggle_dock(DockPosition::Right, window, cx)
 9830        });
 9831        pane.update_in(cx, |pane, window, cx| {
 9832            pane.toggle_zoom(&Default::default(), window, cx)
 9833        });
 9834
 9835        // Opening a dock unzooms the pane.
 9836        workspace.update_in(cx, |workspace, window, cx| {
 9837            workspace.toggle_dock(DockPosition::Right, window, cx)
 9838        });
 9839        workspace.update_in(cx, |workspace, window, cx| {
 9840            let pane = pane.read(cx);
 9841            assert!(!pane.is_zoomed());
 9842            assert!(!pane.focus_handle(cx).is_focused(window));
 9843            assert!(workspace.right_dock().read(cx).is_open());
 9844            assert!(workspace.zoomed.is_none());
 9845        });
 9846    }
 9847
 9848    #[gpui::test]
 9849    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
 9850        init_test(cx);
 9851        let fs = FakeFs::new(cx.executor());
 9852
 9853        let project = Project::test(fs, [], cx).await;
 9854        let (workspace, cx) =
 9855            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9856
 9857        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
 9858            workspace.active_pane().clone()
 9859        });
 9860
 9861        // Add an item to the pane so it can be zoomed
 9862        workspace.update_in(cx, |workspace, window, cx| {
 9863            let item = cx.new(TestItem::new);
 9864            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
 9865        });
 9866
 9867        // Initially not zoomed
 9868        workspace.update_in(cx, |workspace, _window, cx| {
 9869            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
 9870            assert!(
 9871                workspace.zoomed.is_none(),
 9872                "Workspace should track no zoomed pane"
 9873            );
 9874            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
 9875        });
 9876
 9877        // Zoom In
 9878        pane.update_in(cx, |pane, window, cx| {
 9879            pane.zoom_in(&crate::ZoomIn, window, cx);
 9880        });
 9881
 9882        workspace.update_in(cx, |workspace, window, cx| {
 9883            assert!(
 9884                pane.read(cx).is_zoomed(),
 9885                "Pane should be zoomed after ZoomIn"
 9886            );
 9887            assert!(
 9888                workspace.zoomed.is_some(),
 9889                "Workspace should track the zoomed pane"
 9890            );
 9891            assert!(
 9892                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9893                "ZoomIn should focus the pane"
 9894            );
 9895        });
 9896
 9897        // Zoom In again is a no-op
 9898        pane.update_in(cx, |pane, window, cx| {
 9899            pane.zoom_in(&crate::ZoomIn, window, cx);
 9900        });
 9901
 9902        workspace.update_in(cx, |workspace, window, cx| {
 9903            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
 9904            assert!(
 9905                workspace.zoomed.is_some(),
 9906                "Workspace still tracks zoomed pane"
 9907            );
 9908            assert!(
 9909                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9910                "Pane remains focused after repeated ZoomIn"
 9911            );
 9912        });
 9913
 9914        // Zoom Out
 9915        pane.update_in(cx, |pane, window, cx| {
 9916            pane.zoom_out(&crate::ZoomOut, window, cx);
 9917        });
 9918
 9919        workspace.update_in(cx, |workspace, _window, cx| {
 9920            assert!(
 9921                !pane.read(cx).is_zoomed(),
 9922                "Pane should unzoom after ZoomOut"
 9923            );
 9924            assert!(
 9925                workspace.zoomed.is_none(),
 9926                "Workspace clears zoom tracking after ZoomOut"
 9927            );
 9928        });
 9929
 9930        // Zoom Out again is a no-op
 9931        pane.update_in(cx, |pane, window, cx| {
 9932            pane.zoom_out(&crate::ZoomOut, window, cx);
 9933        });
 9934
 9935        workspace.update_in(cx, |workspace, _window, cx| {
 9936            assert!(
 9937                !pane.read(cx).is_zoomed(),
 9938                "Second ZoomOut keeps pane unzoomed"
 9939            );
 9940            assert!(
 9941                workspace.zoomed.is_none(),
 9942                "Workspace remains without zoomed pane"
 9943            );
 9944        });
 9945    }
 9946
 9947    #[gpui::test]
 9948    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
 9949        init_test(cx);
 9950        let fs = FakeFs::new(cx.executor());
 9951
 9952        let project = Project::test(fs, [], cx).await;
 9953        let (workspace, cx) =
 9954            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9955        workspace.update_in(cx, |workspace, window, cx| {
 9956            // Open two docks
 9957            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9958            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9959
 9960            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9961            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9962
 9963            assert!(left_dock.read(cx).is_open());
 9964            assert!(right_dock.read(cx).is_open());
 9965        });
 9966
 9967        workspace.update_in(cx, |workspace, window, cx| {
 9968            // Toggle all docks - should close both
 9969            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9970
 9971            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9972            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9973            assert!(!left_dock.read(cx).is_open());
 9974            assert!(!right_dock.read(cx).is_open());
 9975        });
 9976
 9977        workspace.update_in(cx, |workspace, window, cx| {
 9978            // Toggle again - should reopen both
 9979            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9980
 9981            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9982            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9983            assert!(left_dock.read(cx).is_open());
 9984            assert!(right_dock.read(cx).is_open());
 9985        });
 9986    }
 9987
 9988    #[gpui::test]
 9989    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
 9990        init_test(cx);
 9991        let fs = FakeFs::new(cx.executor());
 9992
 9993        let project = Project::test(fs, [], cx).await;
 9994        let (workspace, cx) =
 9995            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9996        workspace.update_in(cx, |workspace, window, cx| {
 9997            // Open two docks
 9998            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9999            let right_dock = workspace.dock_at_position(DockPosition::Right);
10000
10001            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10002            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10003
10004            assert!(left_dock.read(cx).is_open());
10005            assert!(right_dock.read(cx).is_open());
10006        });
10007
10008        workspace.update_in(cx, |workspace, window, cx| {
10009            // Close them manually
10010            workspace.toggle_dock(DockPosition::Left, window, cx);
10011            workspace.toggle_dock(DockPosition::Right, window, cx);
10012
10013            let left_dock = workspace.dock_at_position(DockPosition::Left);
10014            let right_dock = workspace.dock_at_position(DockPosition::Right);
10015            assert!(!left_dock.read(cx).is_open());
10016            assert!(!right_dock.read(cx).is_open());
10017        });
10018
10019        workspace.update_in(cx, |workspace, window, cx| {
10020            // Toggle all docks - only last closed (right dock) should reopen
10021            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10022
10023            let left_dock = workspace.dock_at_position(DockPosition::Left);
10024            let right_dock = workspace.dock_at_position(DockPosition::Right);
10025            assert!(!left_dock.read(cx).is_open());
10026            assert!(right_dock.read(cx).is_open());
10027        });
10028    }
10029
10030    #[gpui::test]
10031    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10032        init_test(cx);
10033        let fs = FakeFs::new(cx.executor());
10034        let project = Project::test(fs, [], cx).await;
10035        let (workspace, cx) =
10036            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10037
10038        // Open two docks (left and right) with one panel each
10039        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10040            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10041            workspace.add_panel(left_panel.clone(), window, cx);
10042
10043            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10044            workspace.add_panel(right_panel.clone(), window, cx);
10045
10046            workspace.toggle_dock(DockPosition::Left, window, cx);
10047            workspace.toggle_dock(DockPosition::Right, window, cx);
10048
10049            // Verify initial state
10050            assert!(
10051                workspace.left_dock().read(cx).is_open(),
10052                "Left dock should be open"
10053            );
10054            assert_eq!(
10055                workspace
10056                    .left_dock()
10057                    .read(cx)
10058                    .visible_panel()
10059                    .unwrap()
10060                    .panel_id(),
10061                left_panel.panel_id(),
10062                "Left panel should be visible in left dock"
10063            );
10064            assert!(
10065                workspace.right_dock().read(cx).is_open(),
10066                "Right dock should be open"
10067            );
10068            assert_eq!(
10069                workspace
10070                    .right_dock()
10071                    .read(cx)
10072                    .visible_panel()
10073                    .unwrap()
10074                    .panel_id(),
10075                right_panel.panel_id(),
10076                "Right panel should be visible in right dock"
10077            );
10078            assert!(
10079                !workspace.bottom_dock().read(cx).is_open(),
10080                "Bottom dock should be closed"
10081            );
10082
10083            (left_panel, right_panel)
10084        });
10085
10086        // Focus the left panel and move it to the next position (bottom dock)
10087        workspace.update_in(cx, |workspace, window, cx| {
10088            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10089            assert!(
10090                left_panel.read(cx).focus_handle(cx).is_focused(window),
10091                "Left panel should be focused"
10092            );
10093        });
10094
10095        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10096
10097        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10098        workspace.update(cx, |workspace, cx| {
10099            assert!(
10100                !workspace.left_dock().read(cx).is_open(),
10101                "Left dock should be closed"
10102            );
10103            assert!(
10104                workspace.bottom_dock().read(cx).is_open(),
10105                "Bottom dock should now be open"
10106            );
10107            assert_eq!(
10108                left_panel.read(cx).position,
10109                DockPosition::Bottom,
10110                "Left panel should now be in the bottom dock"
10111            );
10112            assert_eq!(
10113                workspace
10114                    .bottom_dock()
10115                    .read(cx)
10116                    .visible_panel()
10117                    .unwrap()
10118                    .panel_id(),
10119                left_panel.panel_id(),
10120                "Left panel should be the visible panel in the bottom dock"
10121            );
10122        });
10123
10124        // Toggle all docks off
10125        workspace.update_in(cx, |workspace, window, cx| {
10126            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10127            assert!(
10128                !workspace.left_dock().read(cx).is_open(),
10129                "Left dock should be closed"
10130            );
10131            assert!(
10132                !workspace.right_dock().read(cx).is_open(),
10133                "Right dock should be closed"
10134            );
10135            assert!(
10136                !workspace.bottom_dock().read(cx).is_open(),
10137                "Bottom dock should be closed"
10138            );
10139        });
10140
10141        // Toggle all docks back on and verify positions are restored
10142        workspace.update_in(cx, |workspace, window, cx| {
10143            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10144            assert!(
10145                !workspace.left_dock().read(cx).is_open(),
10146                "Left dock should remain closed"
10147            );
10148            assert!(
10149                workspace.right_dock().read(cx).is_open(),
10150                "Right dock should remain open"
10151            );
10152            assert!(
10153                workspace.bottom_dock().read(cx).is_open(),
10154                "Bottom dock should remain open"
10155            );
10156            assert_eq!(
10157                left_panel.read(cx).position,
10158                DockPosition::Bottom,
10159                "Left panel should remain in the bottom dock"
10160            );
10161            assert_eq!(
10162                right_panel.read(cx).position,
10163                DockPosition::Right,
10164                "Right panel should remain in the right dock"
10165            );
10166            assert_eq!(
10167                workspace
10168                    .bottom_dock()
10169                    .read(cx)
10170                    .visible_panel()
10171                    .unwrap()
10172                    .panel_id(),
10173                left_panel.panel_id(),
10174                "Left panel should be the visible panel in the right dock"
10175            );
10176        });
10177    }
10178
10179    #[gpui::test]
10180    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10181        init_test(cx);
10182
10183        let fs = FakeFs::new(cx.executor());
10184
10185        let project = Project::test(fs, None, cx).await;
10186        let (workspace, cx) =
10187            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10188
10189        // Let's arrange the panes like this:
10190        //
10191        // +-----------------------+
10192        // |         top           |
10193        // +------+--------+-------+
10194        // | left | center | right |
10195        // +------+--------+-------+
10196        // |        bottom         |
10197        // +-----------------------+
10198
10199        let top_item = cx.new(|cx| {
10200            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10201        });
10202        let bottom_item = cx.new(|cx| {
10203            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10204        });
10205        let left_item = cx.new(|cx| {
10206            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10207        });
10208        let right_item = cx.new(|cx| {
10209            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10210        });
10211        let center_item = cx.new(|cx| {
10212            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10213        });
10214
10215        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10216            let top_pane_id = workspace.active_pane().entity_id();
10217            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10218            workspace.split_pane(
10219                workspace.active_pane().clone(),
10220                SplitDirection::Down,
10221                window,
10222                cx,
10223            );
10224            top_pane_id
10225        });
10226        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10227            let bottom_pane_id = workspace.active_pane().entity_id();
10228            workspace.add_item_to_active_pane(
10229                Box::new(bottom_item.clone()),
10230                None,
10231                false,
10232                window,
10233                cx,
10234            );
10235            workspace.split_pane(
10236                workspace.active_pane().clone(),
10237                SplitDirection::Up,
10238                window,
10239                cx,
10240            );
10241            bottom_pane_id
10242        });
10243        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10244            let left_pane_id = workspace.active_pane().entity_id();
10245            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10246            workspace.split_pane(
10247                workspace.active_pane().clone(),
10248                SplitDirection::Right,
10249                window,
10250                cx,
10251            );
10252            left_pane_id
10253        });
10254        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10255            let right_pane_id = workspace.active_pane().entity_id();
10256            workspace.add_item_to_active_pane(
10257                Box::new(right_item.clone()),
10258                None,
10259                false,
10260                window,
10261                cx,
10262            );
10263            workspace.split_pane(
10264                workspace.active_pane().clone(),
10265                SplitDirection::Left,
10266                window,
10267                cx,
10268            );
10269            right_pane_id
10270        });
10271        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10272            let center_pane_id = workspace.active_pane().entity_id();
10273            workspace.add_item_to_active_pane(
10274                Box::new(center_item.clone()),
10275                None,
10276                false,
10277                window,
10278                cx,
10279            );
10280            center_pane_id
10281        });
10282        cx.executor().run_until_parked();
10283
10284        workspace.update_in(cx, |workspace, window, cx| {
10285            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10286
10287            // Join into next from center pane into right
10288            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10289        });
10290
10291        workspace.update_in(cx, |workspace, window, cx| {
10292            let active_pane = workspace.active_pane();
10293            assert_eq!(right_pane_id, active_pane.entity_id());
10294            assert_eq!(2, active_pane.read(cx).items_len());
10295            let item_ids_in_pane =
10296                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10297            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10298            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10299
10300            // Join into next from right pane into bottom
10301            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10302        });
10303
10304        workspace.update_in(cx, |workspace, window, cx| {
10305            let active_pane = workspace.active_pane();
10306            assert_eq!(bottom_pane_id, active_pane.entity_id());
10307            assert_eq!(3, active_pane.read(cx).items_len());
10308            let item_ids_in_pane =
10309                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10310            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10311            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10312            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10313
10314            // Join into next from bottom pane into left
10315            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10316        });
10317
10318        workspace.update_in(cx, |workspace, window, cx| {
10319            let active_pane = workspace.active_pane();
10320            assert_eq!(left_pane_id, active_pane.entity_id());
10321            assert_eq!(4, active_pane.read(cx).items_len());
10322            let item_ids_in_pane =
10323                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10324            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10325            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10326            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10327            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10328
10329            // Join into next from left pane into top
10330            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10331        });
10332
10333        workspace.update_in(cx, |workspace, window, cx| {
10334            let active_pane = workspace.active_pane();
10335            assert_eq!(top_pane_id, active_pane.entity_id());
10336            assert_eq!(5, active_pane.read(cx).items_len());
10337            let item_ids_in_pane =
10338                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10339            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10340            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10341            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10342            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10343            assert!(item_ids_in_pane.contains(&top_item.item_id()));
10344
10345            // Single pane left: no-op
10346            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10347        });
10348
10349        workspace.update(cx, |workspace, _cx| {
10350            let active_pane = workspace.active_pane();
10351            assert_eq!(top_pane_id, active_pane.entity_id());
10352        });
10353    }
10354
10355    fn add_an_item_to_active_pane(
10356        cx: &mut VisualTestContext,
10357        workspace: &Entity<Workspace>,
10358        item_id: u64,
10359    ) -> Entity<TestItem> {
10360        let item = cx.new(|cx| {
10361            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10362                item_id,
10363                "item{item_id}.txt",
10364                cx,
10365            )])
10366        });
10367        workspace.update_in(cx, |workspace, window, cx| {
10368            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10369        });
10370        item
10371    }
10372
10373    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10374        workspace.update_in(cx, |workspace, window, cx| {
10375            workspace.split_pane(
10376                workspace.active_pane().clone(),
10377                SplitDirection::Right,
10378                window,
10379                cx,
10380            )
10381        })
10382    }
10383
10384    #[gpui::test]
10385    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10386        init_test(cx);
10387        let fs = FakeFs::new(cx.executor());
10388        let project = Project::test(fs, None, cx).await;
10389        let (workspace, cx) =
10390            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10391
10392        add_an_item_to_active_pane(cx, &workspace, 1);
10393        split_pane(cx, &workspace);
10394        add_an_item_to_active_pane(cx, &workspace, 2);
10395        split_pane(cx, &workspace); // empty pane
10396        split_pane(cx, &workspace);
10397        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10398
10399        cx.executor().run_until_parked();
10400
10401        workspace.update(cx, |workspace, cx| {
10402            let num_panes = workspace.panes().len();
10403            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10404            let active_item = workspace
10405                .active_pane()
10406                .read(cx)
10407                .active_item()
10408                .expect("item is in focus");
10409
10410            assert_eq!(num_panes, 4);
10411            assert_eq!(num_items_in_current_pane, 1);
10412            assert_eq!(active_item.item_id(), last_item.item_id());
10413        });
10414
10415        workspace.update_in(cx, |workspace, window, cx| {
10416            workspace.join_all_panes(window, cx);
10417        });
10418
10419        workspace.update(cx, |workspace, cx| {
10420            let num_panes = workspace.panes().len();
10421            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10422            let active_item = workspace
10423                .active_pane()
10424                .read(cx)
10425                .active_item()
10426                .expect("item is in focus");
10427
10428            assert_eq!(num_panes, 1);
10429            assert_eq!(num_items_in_current_pane, 3);
10430            assert_eq!(active_item.item_id(), last_item.item_id());
10431        });
10432    }
10433    struct TestModal(FocusHandle);
10434
10435    impl TestModal {
10436        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10437            Self(cx.focus_handle())
10438        }
10439    }
10440
10441    impl EventEmitter<DismissEvent> for TestModal {}
10442
10443    impl Focusable for TestModal {
10444        fn focus_handle(&self, _cx: &App) -> FocusHandle {
10445            self.0.clone()
10446        }
10447    }
10448
10449    impl ModalView for TestModal {}
10450
10451    impl Render for TestModal {
10452        fn render(
10453            &mut self,
10454            _window: &mut Window,
10455            _cx: &mut Context<TestModal>,
10456        ) -> impl IntoElement {
10457            div().track_focus(&self.0)
10458        }
10459    }
10460
10461    #[gpui::test]
10462    async fn test_panels(cx: &mut gpui::TestAppContext) {
10463        init_test(cx);
10464        let fs = FakeFs::new(cx.executor());
10465
10466        let project = Project::test(fs, [], cx).await;
10467        let (workspace, cx) =
10468            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10469
10470        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10471            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10472            workspace.add_panel(panel_1.clone(), window, cx);
10473            workspace.toggle_dock(DockPosition::Left, window, cx);
10474            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10475            workspace.add_panel(panel_2.clone(), window, cx);
10476            workspace.toggle_dock(DockPosition::Right, window, cx);
10477
10478            let left_dock = workspace.left_dock();
10479            assert_eq!(
10480                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10481                panel_1.panel_id()
10482            );
10483            assert_eq!(
10484                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10485                panel_1.size(window, cx)
10486            );
10487
10488            left_dock.update(cx, |left_dock, cx| {
10489                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10490            });
10491            assert_eq!(
10492                workspace
10493                    .right_dock()
10494                    .read(cx)
10495                    .visible_panel()
10496                    .unwrap()
10497                    .panel_id(),
10498                panel_2.panel_id(),
10499            );
10500
10501            (panel_1, panel_2)
10502        });
10503
10504        // Move panel_1 to the right
10505        panel_1.update_in(cx, |panel_1, window, cx| {
10506            panel_1.set_position(DockPosition::Right, window, cx)
10507        });
10508
10509        workspace.update_in(cx, |workspace, window, cx| {
10510            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10511            // Since it was the only panel on the left, the left dock should now be closed.
10512            assert!(!workspace.left_dock().read(cx).is_open());
10513            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10514            let right_dock = workspace.right_dock();
10515            assert_eq!(
10516                right_dock.read(cx).visible_panel().unwrap().panel_id(),
10517                panel_1.panel_id()
10518            );
10519            assert_eq!(
10520                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10521                px(1337.)
10522            );
10523
10524            // Now we move panel_2 to the left
10525            panel_2.set_position(DockPosition::Left, window, cx);
10526        });
10527
10528        workspace.update(cx, |workspace, cx| {
10529            // Since panel_2 was not visible on the right, we don't open the left dock.
10530            assert!(!workspace.left_dock().read(cx).is_open());
10531            // And the right dock is unaffected in its displaying of panel_1
10532            assert!(workspace.right_dock().read(cx).is_open());
10533            assert_eq!(
10534                workspace
10535                    .right_dock()
10536                    .read(cx)
10537                    .visible_panel()
10538                    .unwrap()
10539                    .panel_id(),
10540                panel_1.panel_id(),
10541            );
10542        });
10543
10544        // Move panel_1 back to the left
10545        panel_1.update_in(cx, |panel_1, window, cx| {
10546            panel_1.set_position(DockPosition::Left, window, cx)
10547        });
10548
10549        workspace.update_in(cx, |workspace, window, cx| {
10550            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10551            let left_dock = workspace.left_dock();
10552            assert!(left_dock.read(cx).is_open());
10553            assert_eq!(
10554                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10555                panel_1.panel_id()
10556            );
10557            assert_eq!(
10558                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10559                px(1337.)
10560            );
10561            // And the right dock should be closed as it no longer has any panels.
10562            assert!(!workspace.right_dock().read(cx).is_open());
10563
10564            // Now we move panel_1 to the bottom
10565            panel_1.set_position(DockPosition::Bottom, window, cx);
10566        });
10567
10568        workspace.update_in(cx, |workspace, window, cx| {
10569            // Since panel_1 was visible on the left, we close the left dock.
10570            assert!(!workspace.left_dock().read(cx).is_open());
10571            // The bottom dock is sized based on the panel's default size,
10572            // since the panel orientation changed from vertical to horizontal.
10573            let bottom_dock = workspace.bottom_dock();
10574            assert_eq!(
10575                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10576                panel_1.size(window, cx),
10577            );
10578            // Close bottom dock and move panel_1 back to the left.
10579            bottom_dock.update(cx, |bottom_dock, cx| {
10580                bottom_dock.set_open(false, window, cx)
10581            });
10582            panel_1.set_position(DockPosition::Left, window, cx);
10583        });
10584
10585        // Emit activated event on panel 1
10586        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10587
10588        // Now the left dock is open and panel_1 is active and focused.
10589        workspace.update_in(cx, |workspace, window, cx| {
10590            let left_dock = workspace.left_dock();
10591            assert!(left_dock.read(cx).is_open());
10592            assert_eq!(
10593                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10594                panel_1.panel_id(),
10595            );
10596            assert!(panel_1.focus_handle(cx).is_focused(window));
10597        });
10598
10599        // Emit closed event on panel 2, which is not active
10600        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10601
10602        // Wo don't close the left dock, because panel_2 wasn't the active panel
10603        workspace.update(cx, |workspace, cx| {
10604            let left_dock = workspace.left_dock();
10605            assert!(left_dock.read(cx).is_open());
10606            assert_eq!(
10607                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10608                panel_1.panel_id(),
10609            );
10610        });
10611
10612        // Emitting a ZoomIn event shows the panel as zoomed.
10613        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10614        workspace.read_with(cx, |workspace, _| {
10615            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10616            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10617        });
10618
10619        // Move panel to another dock while it is zoomed
10620        panel_1.update_in(cx, |panel, window, cx| {
10621            panel.set_position(DockPosition::Right, window, cx)
10622        });
10623        workspace.read_with(cx, |workspace, _| {
10624            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10625
10626            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10627        });
10628
10629        // This is a helper for getting a:
10630        // - valid focus on an element,
10631        // - that isn't a part of the panes and panels system of the Workspace,
10632        // - and doesn't trigger the 'on_focus_lost' API.
10633        let focus_other_view = {
10634            let workspace = workspace.clone();
10635            move |cx: &mut VisualTestContext| {
10636                workspace.update_in(cx, |workspace, window, cx| {
10637                    if workspace.active_modal::<TestModal>(cx).is_some() {
10638                        workspace.toggle_modal(window, cx, TestModal::new);
10639                        workspace.toggle_modal(window, cx, TestModal::new);
10640                    } else {
10641                        workspace.toggle_modal(window, cx, TestModal::new);
10642                    }
10643                })
10644            }
10645        };
10646
10647        // If focus is transferred to another view that's not a panel or another pane, we still show
10648        // the panel as zoomed.
10649        focus_other_view(cx);
10650        workspace.read_with(cx, |workspace, _| {
10651            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10652            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10653        });
10654
10655        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10656        workspace.update_in(cx, |_workspace, window, cx| {
10657            cx.focus_self(window);
10658        });
10659        workspace.read_with(cx, |workspace, _| {
10660            assert_eq!(workspace.zoomed, None);
10661            assert_eq!(workspace.zoomed_position, None);
10662        });
10663
10664        // If focus is transferred again to another view that's not a panel or a pane, we won't
10665        // show the panel as zoomed because it wasn't zoomed before.
10666        focus_other_view(cx);
10667        workspace.read_with(cx, |workspace, _| {
10668            assert_eq!(workspace.zoomed, None);
10669            assert_eq!(workspace.zoomed_position, None);
10670        });
10671
10672        // When the panel is activated, it is zoomed again.
10673        cx.dispatch_action(ToggleRightDock);
10674        workspace.read_with(cx, |workspace, _| {
10675            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10676            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10677        });
10678
10679        // Emitting a ZoomOut event unzooms the panel.
10680        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10681        workspace.read_with(cx, |workspace, _| {
10682            assert_eq!(workspace.zoomed, None);
10683            assert_eq!(workspace.zoomed_position, None);
10684        });
10685
10686        // Emit closed event on panel 1, which is active
10687        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10688
10689        // Now the left dock is closed, because panel_1 was the active panel
10690        workspace.update(cx, |workspace, cx| {
10691            let right_dock = workspace.right_dock();
10692            assert!(!right_dock.read(cx).is_open());
10693        });
10694    }
10695
10696    #[gpui::test]
10697    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10698        init_test(cx);
10699
10700        let fs = FakeFs::new(cx.background_executor.clone());
10701        let project = Project::test(fs, [], cx).await;
10702        let (workspace, cx) =
10703            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10704        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10705
10706        let dirty_regular_buffer = cx.new(|cx| {
10707            TestItem::new(cx)
10708                .with_dirty(true)
10709                .with_label("1.txt")
10710                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10711        });
10712        let dirty_regular_buffer_2 = cx.new(|cx| {
10713            TestItem::new(cx)
10714                .with_dirty(true)
10715                .with_label("2.txt")
10716                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10717        });
10718        let dirty_multi_buffer_with_both = cx.new(|cx| {
10719            TestItem::new(cx)
10720                .with_dirty(true)
10721                .with_buffer_kind(ItemBufferKind::Multibuffer)
10722                .with_label("Fake Project Search")
10723                .with_project_items(&[
10724                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10725                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10726                ])
10727        });
10728        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10729        workspace.update_in(cx, |workspace, window, cx| {
10730            workspace.add_item(
10731                pane.clone(),
10732                Box::new(dirty_regular_buffer.clone()),
10733                None,
10734                false,
10735                false,
10736                window,
10737                cx,
10738            );
10739            workspace.add_item(
10740                pane.clone(),
10741                Box::new(dirty_regular_buffer_2.clone()),
10742                None,
10743                false,
10744                false,
10745                window,
10746                cx,
10747            );
10748            workspace.add_item(
10749                pane.clone(),
10750                Box::new(dirty_multi_buffer_with_both.clone()),
10751                None,
10752                false,
10753                false,
10754                window,
10755                cx,
10756            );
10757        });
10758
10759        pane.update_in(cx, |pane, window, cx| {
10760            pane.activate_item(2, true, true, window, cx);
10761            assert_eq!(
10762                pane.active_item().unwrap().item_id(),
10763                multi_buffer_with_both_files_id,
10764                "Should select the multi buffer in the pane"
10765            );
10766        });
10767        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10768            pane.close_other_items(
10769                &CloseOtherItems {
10770                    save_intent: Some(SaveIntent::Save),
10771                    close_pinned: true,
10772                },
10773                None,
10774                window,
10775                cx,
10776            )
10777        });
10778        cx.background_executor.run_until_parked();
10779        assert!(!cx.has_pending_prompt());
10780        close_all_but_multi_buffer_task
10781            .await
10782            .expect("Closing all buffers but the multi buffer failed");
10783        pane.update(cx, |pane, cx| {
10784            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10785            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10786            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10787            assert_eq!(pane.items_len(), 1);
10788            assert_eq!(
10789                pane.active_item().unwrap().item_id(),
10790                multi_buffer_with_both_files_id,
10791                "Should have only the multi buffer left in the pane"
10792            );
10793            assert!(
10794                dirty_multi_buffer_with_both.read(cx).is_dirty,
10795                "The multi buffer containing the unsaved buffer should still be dirty"
10796            );
10797        });
10798
10799        dirty_regular_buffer.update(cx, |buffer, cx| {
10800            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10801        });
10802
10803        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10804            pane.close_active_item(
10805                &CloseActiveItem {
10806                    save_intent: Some(SaveIntent::Close),
10807                    close_pinned: false,
10808                },
10809                window,
10810                cx,
10811            )
10812        });
10813        cx.background_executor.run_until_parked();
10814        assert!(
10815            cx.has_pending_prompt(),
10816            "Dirty multi buffer should prompt a save dialog"
10817        );
10818        cx.simulate_prompt_answer("Save");
10819        cx.background_executor.run_until_parked();
10820        close_multi_buffer_task
10821            .await
10822            .expect("Closing the multi buffer failed");
10823        pane.update(cx, |pane, cx| {
10824            assert_eq!(
10825                dirty_multi_buffer_with_both.read(cx).save_count,
10826                1,
10827                "Multi buffer item should get be saved"
10828            );
10829            // Test impl does not save inner items, so we do not assert them
10830            assert_eq!(
10831                pane.items_len(),
10832                0,
10833                "No more items should be left in the pane"
10834            );
10835            assert!(pane.active_item().is_none());
10836        });
10837    }
10838
10839    #[gpui::test]
10840    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10841        cx: &mut TestAppContext,
10842    ) {
10843        init_test(cx);
10844
10845        let fs = FakeFs::new(cx.background_executor.clone());
10846        let project = Project::test(fs, [], cx).await;
10847        let (workspace, cx) =
10848            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10849        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10850
10851        let dirty_regular_buffer = cx.new(|cx| {
10852            TestItem::new(cx)
10853                .with_dirty(true)
10854                .with_label("1.txt")
10855                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10856        });
10857        let dirty_regular_buffer_2 = cx.new(|cx| {
10858            TestItem::new(cx)
10859                .with_dirty(true)
10860                .with_label("2.txt")
10861                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10862        });
10863        let clear_regular_buffer = cx.new(|cx| {
10864            TestItem::new(cx)
10865                .with_label("3.txt")
10866                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10867        });
10868
10869        let dirty_multi_buffer_with_both = cx.new(|cx| {
10870            TestItem::new(cx)
10871                .with_dirty(true)
10872                .with_buffer_kind(ItemBufferKind::Multibuffer)
10873                .with_label("Fake Project Search")
10874                .with_project_items(&[
10875                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10876                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10877                    clear_regular_buffer.read(cx).project_items[0].clone(),
10878                ])
10879        });
10880        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10881        workspace.update_in(cx, |workspace, window, cx| {
10882            workspace.add_item(
10883                pane.clone(),
10884                Box::new(dirty_regular_buffer.clone()),
10885                None,
10886                false,
10887                false,
10888                window,
10889                cx,
10890            );
10891            workspace.add_item(
10892                pane.clone(),
10893                Box::new(dirty_multi_buffer_with_both.clone()),
10894                None,
10895                false,
10896                false,
10897                window,
10898                cx,
10899            );
10900        });
10901
10902        pane.update_in(cx, |pane, window, cx| {
10903            pane.activate_item(1, true, true, window, cx);
10904            assert_eq!(
10905                pane.active_item().unwrap().item_id(),
10906                multi_buffer_with_both_files_id,
10907                "Should select the multi buffer in the pane"
10908            );
10909        });
10910        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10911            pane.close_active_item(
10912                &CloseActiveItem {
10913                    save_intent: None,
10914                    close_pinned: false,
10915                },
10916                window,
10917                cx,
10918            )
10919        });
10920        cx.background_executor.run_until_parked();
10921        assert!(
10922            cx.has_pending_prompt(),
10923            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10924        );
10925    }
10926
10927    /// Tests that when `close_on_file_delete` is enabled, files are automatically
10928    /// closed when they are deleted from disk.
10929    #[gpui::test]
10930    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10931        init_test(cx);
10932
10933        // Enable the close_on_disk_deletion setting
10934        cx.update_global(|store: &mut SettingsStore, cx| {
10935            store.update_user_settings(cx, |settings| {
10936                settings.workspace.close_on_file_delete = Some(true);
10937            });
10938        });
10939
10940        let fs = FakeFs::new(cx.background_executor.clone());
10941        let project = Project::test(fs, [], cx).await;
10942        let (workspace, cx) =
10943            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10944        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10945
10946        // Create a test item that simulates a file
10947        let item = cx.new(|cx| {
10948            TestItem::new(cx)
10949                .with_label("test.txt")
10950                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10951        });
10952
10953        // Add item to workspace
10954        workspace.update_in(cx, |workspace, window, cx| {
10955            workspace.add_item(
10956                pane.clone(),
10957                Box::new(item.clone()),
10958                None,
10959                false,
10960                false,
10961                window,
10962                cx,
10963            );
10964        });
10965
10966        // Verify the item is in the pane
10967        pane.read_with(cx, |pane, _| {
10968            assert_eq!(pane.items().count(), 1);
10969        });
10970
10971        // Simulate file deletion by setting the item's deleted state
10972        item.update(cx, |item, _| {
10973            item.set_has_deleted_file(true);
10974        });
10975
10976        // Emit UpdateTab event to trigger the close behavior
10977        cx.run_until_parked();
10978        item.update(cx, |_, cx| {
10979            cx.emit(ItemEvent::UpdateTab);
10980        });
10981
10982        // Allow the close operation to complete
10983        cx.run_until_parked();
10984
10985        // Verify the item was automatically closed
10986        pane.read_with(cx, |pane, _| {
10987            assert_eq!(
10988                pane.items().count(),
10989                0,
10990                "Item should be automatically closed when file is deleted"
10991            );
10992        });
10993    }
10994
10995    /// Tests that when `close_on_file_delete` is disabled (default), files remain
10996    /// open with a strikethrough when they are deleted from disk.
10997    #[gpui::test]
10998    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10999        init_test(cx);
11000
11001        // Ensure close_on_disk_deletion is disabled (default)
11002        cx.update_global(|store: &mut SettingsStore, cx| {
11003            store.update_user_settings(cx, |settings| {
11004                settings.workspace.close_on_file_delete = Some(false);
11005            });
11006        });
11007
11008        let fs = FakeFs::new(cx.background_executor.clone());
11009        let project = Project::test(fs, [], cx).await;
11010        let (workspace, cx) =
11011            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11012        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11013
11014        // Create a test item that simulates a file
11015        let item = cx.new(|cx| {
11016            TestItem::new(cx)
11017                .with_label("test.txt")
11018                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11019        });
11020
11021        // Add item to workspace
11022        workspace.update_in(cx, |workspace, window, cx| {
11023            workspace.add_item(
11024                pane.clone(),
11025                Box::new(item.clone()),
11026                None,
11027                false,
11028                false,
11029                window,
11030                cx,
11031            );
11032        });
11033
11034        // Verify the item is in the pane
11035        pane.read_with(cx, |pane, _| {
11036            assert_eq!(pane.items().count(), 1);
11037        });
11038
11039        // Simulate file deletion
11040        item.update(cx, |item, _| {
11041            item.set_has_deleted_file(true);
11042        });
11043
11044        // Emit UpdateTab event
11045        cx.run_until_parked();
11046        item.update(cx, |_, cx| {
11047            cx.emit(ItemEvent::UpdateTab);
11048        });
11049
11050        // Allow any potential close operation to complete
11051        cx.run_until_parked();
11052
11053        // Verify the item remains open (with strikethrough)
11054        pane.read_with(cx, |pane, _| {
11055            assert_eq!(
11056                pane.items().count(),
11057                1,
11058                "Item should remain open when close_on_disk_deletion is disabled"
11059            );
11060        });
11061
11062        // Verify the item shows as deleted
11063        item.read_with(cx, |item, _| {
11064            assert!(
11065                item.has_deleted_file,
11066                "Item should be marked as having deleted file"
11067            );
11068        });
11069    }
11070
11071    /// Tests that dirty files are not automatically closed when deleted from disk,
11072    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11073    /// unsaved changes without being prompted.
11074    #[gpui::test]
11075    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11076        init_test(cx);
11077
11078        // Enable the close_on_file_delete setting
11079        cx.update_global(|store: &mut SettingsStore, cx| {
11080            store.update_user_settings(cx, |settings| {
11081                settings.workspace.close_on_file_delete = Some(true);
11082            });
11083        });
11084
11085        let fs = FakeFs::new(cx.background_executor.clone());
11086        let project = Project::test(fs, [], cx).await;
11087        let (workspace, cx) =
11088            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11089        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11090
11091        // Create a dirty test item
11092        let item = cx.new(|cx| {
11093            TestItem::new(cx)
11094                .with_dirty(true)
11095                .with_label("test.txt")
11096                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11097        });
11098
11099        // Add item to workspace
11100        workspace.update_in(cx, |workspace, window, cx| {
11101            workspace.add_item(
11102                pane.clone(),
11103                Box::new(item.clone()),
11104                None,
11105                false,
11106                false,
11107                window,
11108                cx,
11109            );
11110        });
11111
11112        // Simulate file deletion
11113        item.update(cx, |item, _| {
11114            item.set_has_deleted_file(true);
11115        });
11116
11117        // Emit UpdateTab event to trigger the close behavior
11118        cx.run_until_parked();
11119        item.update(cx, |_, cx| {
11120            cx.emit(ItemEvent::UpdateTab);
11121        });
11122
11123        // Allow any potential close operation to complete
11124        cx.run_until_parked();
11125
11126        // Verify the item remains open (dirty files are not auto-closed)
11127        pane.read_with(cx, |pane, _| {
11128            assert_eq!(
11129                pane.items().count(),
11130                1,
11131                "Dirty items should not be automatically closed even when file is deleted"
11132            );
11133        });
11134
11135        // Verify the item is marked as deleted and still dirty
11136        item.read_with(cx, |item, _| {
11137            assert!(
11138                item.has_deleted_file,
11139                "Item should be marked as having deleted file"
11140            );
11141            assert!(item.is_dirty, "Item should still be dirty");
11142        });
11143    }
11144
11145    /// Tests that navigation history is cleaned up when files are auto-closed
11146    /// due to deletion from disk.
11147    #[gpui::test]
11148    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11149        init_test(cx);
11150
11151        // Enable the close_on_file_delete setting
11152        cx.update_global(|store: &mut SettingsStore, cx| {
11153            store.update_user_settings(cx, |settings| {
11154                settings.workspace.close_on_file_delete = Some(true);
11155            });
11156        });
11157
11158        let fs = FakeFs::new(cx.background_executor.clone());
11159        let project = Project::test(fs, [], cx).await;
11160        let (workspace, cx) =
11161            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11162        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11163
11164        // Create test items
11165        let item1 = cx.new(|cx| {
11166            TestItem::new(cx)
11167                .with_label("test1.txt")
11168                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11169        });
11170        let item1_id = item1.item_id();
11171
11172        let item2 = cx.new(|cx| {
11173            TestItem::new(cx)
11174                .with_label("test2.txt")
11175                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11176        });
11177
11178        // Add items to workspace
11179        workspace.update_in(cx, |workspace, window, cx| {
11180            workspace.add_item(
11181                pane.clone(),
11182                Box::new(item1.clone()),
11183                None,
11184                false,
11185                false,
11186                window,
11187                cx,
11188            );
11189            workspace.add_item(
11190                pane.clone(),
11191                Box::new(item2.clone()),
11192                None,
11193                false,
11194                false,
11195                window,
11196                cx,
11197            );
11198        });
11199
11200        // Activate item1 to ensure it gets navigation entries
11201        pane.update_in(cx, |pane, window, cx| {
11202            pane.activate_item(0, true, true, window, cx);
11203        });
11204
11205        // Switch to item2 and back to create navigation history
11206        pane.update_in(cx, |pane, window, cx| {
11207            pane.activate_item(1, true, true, window, cx);
11208        });
11209        cx.run_until_parked();
11210
11211        pane.update_in(cx, |pane, window, cx| {
11212            pane.activate_item(0, true, true, window, cx);
11213        });
11214        cx.run_until_parked();
11215
11216        // Simulate file deletion for item1
11217        item1.update(cx, |item, _| {
11218            item.set_has_deleted_file(true);
11219        });
11220
11221        // Emit UpdateTab event to trigger the close behavior
11222        item1.update(cx, |_, cx| {
11223            cx.emit(ItemEvent::UpdateTab);
11224        });
11225        cx.run_until_parked();
11226
11227        // Verify item1 was closed
11228        pane.read_with(cx, |pane, _| {
11229            assert_eq!(
11230                pane.items().count(),
11231                1,
11232                "Should have 1 item remaining after auto-close"
11233            );
11234        });
11235
11236        // Check navigation history after close
11237        let has_item = pane.read_with(cx, |pane, cx| {
11238            let mut has_item = false;
11239            pane.nav_history().for_each_entry(cx, |entry, _| {
11240                if entry.item.id() == item1_id {
11241                    has_item = true;
11242                }
11243            });
11244            has_item
11245        });
11246
11247        assert!(
11248            !has_item,
11249            "Navigation history should not contain closed item entries"
11250        );
11251    }
11252
11253    #[gpui::test]
11254    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11255        cx: &mut TestAppContext,
11256    ) {
11257        init_test(cx);
11258
11259        let fs = FakeFs::new(cx.background_executor.clone());
11260        let project = Project::test(fs, [], cx).await;
11261        let (workspace, cx) =
11262            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11263        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11264
11265        let dirty_regular_buffer = cx.new(|cx| {
11266            TestItem::new(cx)
11267                .with_dirty(true)
11268                .with_label("1.txt")
11269                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11270        });
11271        let dirty_regular_buffer_2 = cx.new(|cx| {
11272            TestItem::new(cx)
11273                .with_dirty(true)
11274                .with_label("2.txt")
11275                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11276        });
11277        let clear_regular_buffer = cx.new(|cx| {
11278            TestItem::new(cx)
11279                .with_label("3.txt")
11280                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11281        });
11282
11283        let dirty_multi_buffer = cx.new(|cx| {
11284            TestItem::new(cx)
11285                .with_dirty(true)
11286                .with_buffer_kind(ItemBufferKind::Multibuffer)
11287                .with_label("Fake Project Search")
11288                .with_project_items(&[
11289                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11290                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11291                    clear_regular_buffer.read(cx).project_items[0].clone(),
11292                ])
11293        });
11294        workspace.update_in(cx, |workspace, window, cx| {
11295            workspace.add_item(
11296                pane.clone(),
11297                Box::new(dirty_regular_buffer.clone()),
11298                None,
11299                false,
11300                false,
11301                window,
11302                cx,
11303            );
11304            workspace.add_item(
11305                pane.clone(),
11306                Box::new(dirty_regular_buffer_2.clone()),
11307                None,
11308                false,
11309                false,
11310                window,
11311                cx,
11312            );
11313            workspace.add_item(
11314                pane.clone(),
11315                Box::new(dirty_multi_buffer.clone()),
11316                None,
11317                false,
11318                false,
11319                window,
11320                cx,
11321            );
11322        });
11323
11324        pane.update_in(cx, |pane, window, cx| {
11325            pane.activate_item(2, true, true, window, cx);
11326            assert_eq!(
11327                pane.active_item().unwrap().item_id(),
11328                dirty_multi_buffer.item_id(),
11329                "Should select the multi buffer in the pane"
11330            );
11331        });
11332        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11333            pane.close_active_item(
11334                &CloseActiveItem {
11335                    save_intent: None,
11336                    close_pinned: false,
11337                },
11338                window,
11339                cx,
11340            )
11341        });
11342        cx.background_executor.run_until_parked();
11343        assert!(
11344            !cx.has_pending_prompt(),
11345            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11346        );
11347        close_multi_buffer_task
11348            .await
11349            .expect("Closing multi buffer failed");
11350        pane.update(cx, |pane, cx| {
11351            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11352            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11353            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11354            assert_eq!(
11355                pane.items()
11356                    .map(|item| item.item_id())
11357                    .sorted()
11358                    .collect::<Vec<_>>(),
11359                vec![
11360                    dirty_regular_buffer.item_id(),
11361                    dirty_regular_buffer_2.item_id(),
11362                ],
11363                "Should have no multi buffer left in the pane"
11364            );
11365            assert!(dirty_regular_buffer.read(cx).is_dirty);
11366            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11367        });
11368    }
11369
11370    #[gpui::test]
11371    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11372        init_test(cx);
11373        let fs = FakeFs::new(cx.executor());
11374        let project = Project::test(fs, [], cx).await;
11375        let (workspace, cx) =
11376            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11377
11378        // Add a new panel to the right dock, opening the dock and setting the
11379        // focus to the new panel.
11380        let panel = workspace.update_in(cx, |workspace, window, cx| {
11381            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11382            workspace.add_panel(panel.clone(), window, cx);
11383
11384            workspace
11385                .right_dock()
11386                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11387
11388            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11389
11390            panel
11391        });
11392
11393        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11394        // panel to the next valid position which, in this case, is the left
11395        // dock.
11396        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11397        workspace.update(cx, |workspace, cx| {
11398            assert!(workspace.left_dock().read(cx).is_open());
11399            assert_eq!(panel.read(cx).position, DockPosition::Left);
11400        });
11401
11402        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11403        // panel to the next valid position which, in this case, is the bottom
11404        // dock.
11405        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11406        workspace.update(cx, |workspace, cx| {
11407            assert!(workspace.bottom_dock().read(cx).is_open());
11408            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11409        });
11410
11411        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11412        // around moving the panel to its initial position, the right dock.
11413        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11414        workspace.update(cx, |workspace, cx| {
11415            assert!(workspace.right_dock().read(cx).is_open());
11416            assert_eq!(panel.read(cx).position, DockPosition::Right);
11417        });
11418
11419        // Remove focus from the panel, ensuring that, if the panel is not
11420        // focused, the `MoveFocusedPanelToNextPosition` action does not update
11421        // the panel's position, so the panel is still in the right dock.
11422        workspace.update_in(cx, |workspace, window, cx| {
11423            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11424        });
11425
11426        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11427        workspace.update(cx, |workspace, cx| {
11428            assert!(workspace.right_dock().read(cx).is_open());
11429            assert_eq!(panel.read(cx).position, DockPosition::Right);
11430        });
11431    }
11432
11433    #[gpui::test]
11434    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11435        init_test(cx);
11436
11437        let fs = FakeFs::new(cx.executor());
11438        let project = Project::test(fs, [], cx).await;
11439        let (workspace, cx) =
11440            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11441
11442        let item_1 = cx.new(|cx| {
11443            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11444        });
11445        workspace.update_in(cx, |workspace, window, cx| {
11446            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11447            workspace.move_item_to_pane_in_direction(
11448                &MoveItemToPaneInDirection {
11449                    direction: SplitDirection::Right,
11450                    focus: true,
11451                    clone: false,
11452                },
11453                window,
11454                cx,
11455            );
11456            workspace.move_item_to_pane_at_index(
11457                &MoveItemToPane {
11458                    destination: 3,
11459                    focus: true,
11460                    clone: false,
11461                },
11462                window,
11463                cx,
11464            );
11465
11466            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11467            assert_eq!(
11468                pane_items_paths(&workspace.active_pane, cx),
11469                vec!["first.txt".to_string()],
11470                "Single item was not moved anywhere"
11471            );
11472        });
11473
11474        let item_2 = cx.new(|cx| {
11475            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11476        });
11477        workspace.update_in(cx, |workspace, window, cx| {
11478            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11479            assert_eq!(
11480                pane_items_paths(&workspace.panes[0], cx),
11481                vec!["first.txt".to_string(), "second.txt".to_string()],
11482            );
11483            workspace.move_item_to_pane_in_direction(
11484                &MoveItemToPaneInDirection {
11485                    direction: SplitDirection::Right,
11486                    focus: true,
11487                    clone: false,
11488                },
11489                window,
11490                cx,
11491            );
11492
11493            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11494            assert_eq!(
11495                pane_items_paths(&workspace.panes[0], cx),
11496                vec!["first.txt".to_string()],
11497                "After moving, one item should be left in the original pane"
11498            );
11499            assert_eq!(
11500                pane_items_paths(&workspace.panes[1], cx),
11501                vec!["second.txt".to_string()],
11502                "New item should have been moved to the new pane"
11503            );
11504        });
11505
11506        let item_3 = cx.new(|cx| {
11507            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11508        });
11509        workspace.update_in(cx, |workspace, window, cx| {
11510            let original_pane = workspace.panes[0].clone();
11511            workspace.set_active_pane(&original_pane, window, cx);
11512            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11513            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11514            assert_eq!(
11515                pane_items_paths(&workspace.active_pane, cx),
11516                vec!["first.txt".to_string(), "third.txt".to_string()],
11517                "New pane should be ready to move one item out"
11518            );
11519
11520            workspace.move_item_to_pane_at_index(
11521                &MoveItemToPane {
11522                    destination: 3,
11523                    focus: true,
11524                    clone: false,
11525                },
11526                window,
11527                cx,
11528            );
11529            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11530            assert_eq!(
11531                pane_items_paths(&workspace.active_pane, cx),
11532                vec!["first.txt".to_string()],
11533                "After moving, one item should be left in the original pane"
11534            );
11535            assert_eq!(
11536                pane_items_paths(&workspace.panes[1], cx),
11537                vec!["second.txt".to_string()],
11538                "Previously created pane should be unchanged"
11539            );
11540            assert_eq!(
11541                pane_items_paths(&workspace.panes[2], cx),
11542                vec!["third.txt".to_string()],
11543                "New item should have been moved to the new pane"
11544            );
11545        });
11546    }
11547
11548    #[gpui::test]
11549    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11550        init_test(cx);
11551
11552        let fs = FakeFs::new(cx.executor());
11553        let project = Project::test(fs, [], cx).await;
11554        let (workspace, cx) =
11555            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11556
11557        let item_1 = cx.new(|cx| {
11558            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11559        });
11560        workspace.update_in(cx, |workspace, window, cx| {
11561            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11562            workspace.move_item_to_pane_in_direction(
11563                &MoveItemToPaneInDirection {
11564                    direction: SplitDirection::Right,
11565                    focus: true,
11566                    clone: true,
11567                },
11568                window,
11569                cx,
11570            );
11571            workspace.move_item_to_pane_at_index(
11572                &MoveItemToPane {
11573                    destination: 3,
11574                    focus: true,
11575                    clone: true,
11576                },
11577                window,
11578                cx,
11579            );
11580        });
11581        cx.run_until_parked();
11582
11583        workspace.update(cx, |workspace, cx| {
11584            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11585            for pane in workspace.panes() {
11586                assert_eq!(
11587                    pane_items_paths(pane, cx),
11588                    vec!["first.txt".to_string()],
11589                    "Single item exists in all panes"
11590                );
11591            }
11592        });
11593
11594        // verify that the active pane has been updated after waiting for the
11595        // pane focus event to fire and resolve
11596        workspace.read_with(cx, |workspace, _app| {
11597            assert_eq!(
11598                workspace.active_pane(),
11599                &workspace.panes[2],
11600                "The third pane should be the active one: {:?}",
11601                workspace.panes
11602            );
11603        })
11604    }
11605
11606    mod register_project_item_tests {
11607
11608        use super::*;
11609
11610        // View
11611        struct TestPngItemView {
11612            focus_handle: FocusHandle,
11613        }
11614        // Model
11615        struct TestPngItem {}
11616
11617        impl project::ProjectItem for TestPngItem {
11618            fn try_open(
11619                _project: &Entity<Project>,
11620                path: &ProjectPath,
11621                cx: &mut App,
11622            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11623                if path.path.extension().unwrap() == "png" {
11624                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11625                } else {
11626                    None
11627                }
11628            }
11629
11630            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11631                None
11632            }
11633
11634            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11635                None
11636            }
11637
11638            fn is_dirty(&self) -> bool {
11639                false
11640            }
11641        }
11642
11643        impl Item for TestPngItemView {
11644            type Event = ();
11645            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11646                "".into()
11647            }
11648        }
11649        impl EventEmitter<()> for TestPngItemView {}
11650        impl Focusable for TestPngItemView {
11651            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11652                self.focus_handle.clone()
11653            }
11654        }
11655
11656        impl Render for TestPngItemView {
11657            fn render(
11658                &mut self,
11659                _window: &mut Window,
11660                _cx: &mut Context<Self>,
11661            ) -> impl IntoElement {
11662                Empty
11663            }
11664        }
11665
11666        impl ProjectItem for TestPngItemView {
11667            type Item = TestPngItem;
11668
11669            fn for_project_item(
11670                _project: Entity<Project>,
11671                _pane: Option<&Pane>,
11672                _item: Entity<Self::Item>,
11673                _: &mut Window,
11674                cx: &mut Context<Self>,
11675            ) -> Self
11676            where
11677                Self: Sized,
11678            {
11679                Self {
11680                    focus_handle: cx.focus_handle(),
11681                }
11682            }
11683        }
11684
11685        // View
11686        struct TestIpynbItemView {
11687            focus_handle: FocusHandle,
11688        }
11689        // Model
11690        struct TestIpynbItem {}
11691
11692        impl project::ProjectItem for TestIpynbItem {
11693            fn try_open(
11694                _project: &Entity<Project>,
11695                path: &ProjectPath,
11696                cx: &mut App,
11697            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11698                if path.path.extension().unwrap() == "ipynb" {
11699                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11700                } else {
11701                    None
11702                }
11703            }
11704
11705            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11706                None
11707            }
11708
11709            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11710                None
11711            }
11712
11713            fn is_dirty(&self) -> bool {
11714                false
11715            }
11716        }
11717
11718        impl Item for TestIpynbItemView {
11719            type Event = ();
11720            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11721                "".into()
11722            }
11723        }
11724        impl EventEmitter<()> for TestIpynbItemView {}
11725        impl Focusable for TestIpynbItemView {
11726            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11727                self.focus_handle.clone()
11728            }
11729        }
11730
11731        impl Render for TestIpynbItemView {
11732            fn render(
11733                &mut self,
11734                _window: &mut Window,
11735                _cx: &mut Context<Self>,
11736            ) -> impl IntoElement {
11737                Empty
11738            }
11739        }
11740
11741        impl ProjectItem for TestIpynbItemView {
11742            type Item = TestIpynbItem;
11743
11744            fn for_project_item(
11745                _project: Entity<Project>,
11746                _pane: Option<&Pane>,
11747                _item: Entity<Self::Item>,
11748                _: &mut Window,
11749                cx: &mut Context<Self>,
11750            ) -> Self
11751            where
11752                Self: Sized,
11753            {
11754                Self {
11755                    focus_handle: cx.focus_handle(),
11756                }
11757            }
11758        }
11759
11760        struct TestAlternatePngItemView {
11761            focus_handle: FocusHandle,
11762        }
11763
11764        impl Item for TestAlternatePngItemView {
11765            type Event = ();
11766            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11767                "".into()
11768            }
11769        }
11770
11771        impl EventEmitter<()> for TestAlternatePngItemView {}
11772        impl Focusable for TestAlternatePngItemView {
11773            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11774                self.focus_handle.clone()
11775            }
11776        }
11777
11778        impl Render for TestAlternatePngItemView {
11779            fn render(
11780                &mut self,
11781                _window: &mut Window,
11782                _cx: &mut Context<Self>,
11783            ) -> impl IntoElement {
11784                Empty
11785            }
11786        }
11787
11788        impl ProjectItem for TestAlternatePngItemView {
11789            type Item = TestPngItem;
11790
11791            fn for_project_item(
11792                _project: Entity<Project>,
11793                _pane: Option<&Pane>,
11794                _item: Entity<Self::Item>,
11795                _: &mut Window,
11796                cx: &mut Context<Self>,
11797            ) -> Self
11798            where
11799                Self: Sized,
11800            {
11801                Self {
11802                    focus_handle: cx.focus_handle(),
11803                }
11804            }
11805        }
11806
11807        #[gpui::test]
11808        async fn test_register_project_item(cx: &mut TestAppContext) {
11809            init_test(cx);
11810
11811            cx.update(|cx| {
11812                register_project_item::<TestPngItemView>(cx);
11813                register_project_item::<TestIpynbItemView>(cx);
11814            });
11815
11816            let fs = FakeFs::new(cx.executor());
11817            fs.insert_tree(
11818                "/root1",
11819                json!({
11820                    "one.png": "BINARYDATAHERE",
11821                    "two.ipynb": "{ totally a notebook }",
11822                    "three.txt": "editing text, sure why not?"
11823                }),
11824            )
11825            .await;
11826
11827            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11828            let (workspace, cx) =
11829                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11830
11831            let worktree_id = project.update(cx, |project, cx| {
11832                project.worktrees(cx).next().unwrap().read(cx).id()
11833            });
11834
11835            let handle = workspace
11836                .update_in(cx, |workspace, window, cx| {
11837                    let project_path = (worktree_id, rel_path("one.png"));
11838                    workspace.open_path(project_path, None, true, window, cx)
11839                })
11840                .await
11841                .unwrap();
11842
11843            // Now we can check if the handle we got back errored or not
11844            assert_eq!(
11845                handle.to_any_view().entity_type(),
11846                TypeId::of::<TestPngItemView>()
11847            );
11848
11849            let handle = workspace
11850                .update_in(cx, |workspace, window, cx| {
11851                    let project_path = (worktree_id, rel_path("two.ipynb"));
11852                    workspace.open_path(project_path, None, true, window, cx)
11853                })
11854                .await
11855                .unwrap();
11856
11857            assert_eq!(
11858                handle.to_any_view().entity_type(),
11859                TypeId::of::<TestIpynbItemView>()
11860            );
11861
11862            let handle = workspace
11863                .update_in(cx, |workspace, window, cx| {
11864                    let project_path = (worktree_id, rel_path("three.txt"));
11865                    workspace.open_path(project_path, None, true, window, cx)
11866                })
11867                .await;
11868            assert!(handle.is_err());
11869        }
11870
11871        #[gpui::test]
11872        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11873            init_test(cx);
11874
11875            cx.update(|cx| {
11876                register_project_item::<TestPngItemView>(cx);
11877                register_project_item::<TestAlternatePngItemView>(cx);
11878            });
11879
11880            let fs = FakeFs::new(cx.executor());
11881            fs.insert_tree(
11882                "/root1",
11883                json!({
11884                    "one.png": "BINARYDATAHERE",
11885                    "two.ipynb": "{ totally a notebook }",
11886                    "three.txt": "editing text, sure why not?"
11887                }),
11888            )
11889            .await;
11890            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11891            let (workspace, cx) =
11892                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11893            let worktree_id = project.update(cx, |project, cx| {
11894                project.worktrees(cx).next().unwrap().read(cx).id()
11895            });
11896
11897            let handle = workspace
11898                .update_in(cx, |workspace, window, cx| {
11899                    let project_path = (worktree_id, rel_path("one.png"));
11900                    workspace.open_path(project_path, None, true, window, cx)
11901                })
11902                .await
11903                .unwrap();
11904
11905            // This _must_ be the second item registered
11906            assert_eq!(
11907                handle.to_any_view().entity_type(),
11908                TypeId::of::<TestAlternatePngItemView>()
11909            );
11910
11911            let handle = workspace
11912                .update_in(cx, |workspace, window, cx| {
11913                    let project_path = (worktree_id, rel_path("three.txt"));
11914                    workspace.open_path(project_path, None, true, window, cx)
11915                })
11916                .await;
11917            assert!(handle.is_err());
11918        }
11919    }
11920
11921    #[gpui::test]
11922    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11923        init_test(cx);
11924
11925        let fs = FakeFs::new(cx.executor());
11926        let project = Project::test(fs, [], cx).await;
11927        let (workspace, _cx) =
11928            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11929
11930        // Test with status bar shown (default)
11931        workspace.read_with(cx, |workspace, cx| {
11932            let visible = workspace.status_bar_visible(cx);
11933            assert!(visible, "Status bar should be visible by default");
11934        });
11935
11936        // Test with status bar hidden
11937        cx.update_global(|store: &mut SettingsStore, cx| {
11938            store.update_user_settings(cx, |settings| {
11939                settings.status_bar.get_or_insert_default().show = Some(false);
11940            });
11941        });
11942
11943        workspace.read_with(cx, |workspace, cx| {
11944            let visible = workspace.status_bar_visible(cx);
11945            assert!(!visible, "Status bar should be hidden when show is false");
11946        });
11947
11948        // Test with status bar shown explicitly
11949        cx.update_global(|store: &mut SettingsStore, cx| {
11950            store.update_user_settings(cx, |settings| {
11951                settings.status_bar.get_or_insert_default().show = Some(true);
11952            });
11953        });
11954
11955        workspace.read_with(cx, |workspace, cx| {
11956            let visible = workspace.status_bar_visible(cx);
11957            assert!(visible, "Status bar should be visible when show is true");
11958        });
11959    }
11960
11961    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11962        pane.read(cx)
11963            .items()
11964            .flat_map(|item| {
11965                item.project_paths(cx)
11966                    .into_iter()
11967                    .map(|path| path.path.display(PathStyle::local()).into_owned())
11968            })
11969            .collect()
11970    }
11971
11972    pub fn init_test(cx: &mut TestAppContext) {
11973        cx.update(|cx| {
11974            let settings_store = SettingsStore::test(cx);
11975            cx.set_global(settings_store);
11976            theme::init(theme::LoadThemes::JustBase, cx);
11977        });
11978    }
11979
11980    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11981        let item = TestProjectItem::new(id, path, cx);
11982        item.update(cx, |item, _| {
11983            item.is_dirty = true;
11984        });
11985        item
11986    }
11987}