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