workspace.rs

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