workspace.rs

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