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