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                    None,
 2781                    window,
 2782                    cx,
 2783                )
 2784            });
 2785
 2786            tasks.push(current_pane_close);
 2787        }
 2788
 2789        for pane in self.panes() {
 2790            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 2791                continue;
 2792            }
 2793
 2794            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 2795                pane.close_all_items(
 2796                    &CloseAllItems {
 2797                        save_intent: Some(save_intent),
 2798                        close_pinned: false,
 2799                    },
 2800                    window,
 2801                    cx,
 2802                )
 2803            });
 2804
 2805            tasks.push(close_pane_items)
 2806        }
 2807
 2808        if tasks.is_empty() {
 2809            None
 2810        } else {
 2811            Some(cx.spawn_in(window, async move |_, _| {
 2812                for task in tasks {
 2813                    task.await?
 2814                }
 2815                Ok(())
 2816            }))
 2817        }
 2818    }
 2819
 2820    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 2821        self.dock_at_position(position).read(cx).is_open()
 2822    }
 2823
 2824    pub fn toggle_dock(
 2825        &mut self,
 2826        dock_side: DockPosition,
 2827        window: &mut Window,
 2828        cx: &mut Context<Self>,
 2829    ) {
 2830        let dock = self.dock_at_position(dock_side);
 2831        let mut focus_center = false;
 2832        let mut reveal_dock = false;
 2833        dock.update(cx, |dock, cx| {
 2834            let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 2835            let was_visible = dock.is_open() && !other_is_zoomed;
 2836            dock.set_open(!was_visible, window, cx);
 2837
 2838            if dock.active_panel().is_none() {
 2839                let Some(panel_ix) = dock
 2840                    .first_enabled_panel_idx(cx)
 2841                    .log_with_level(log::Level::Info)
 2842                else {
 2843                    return;
 2844                };
 2845                dock.activate_panel(panel_ix, window, cx);
 2846            }
 2847
 2848            if let Some(active_panel) = dock.active_panel() {
 2849                if was_visible {
 2850                    if active_panel
 2851                        .panel_focus_handle(cx)
 2852                        .contains_focused(window, cx)
 2853                    {
 2854                        focus_center = true;
 2855                    }
 2856                } else {
 2857                    let focus_handle = &active_panel.panel_focus_handle(cx);
 2858                    window.focus(focus_handle);
 2859                    reveal_dock = true;
 2860                }
 2861            }
 2862        });
 2863
 2864        if reveal_dock {
 2865            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 2866        }
 2867
 2868        if focus_center {
 2869            self.active_pane
 2870                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 2871        }
 2872
 2873        cx.notify();
 2874        self.serialize_workspace(window, cx);
 2875    }
 2876
 2877    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 2878        self.all_docks().into_iter().find(|&dock| {
 2879            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 2880        })
 2881    }
 2882
 2883    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 2884        if let Some(dock) = self.active_dock(window, cx) {
 2885            dock.update(cx, |dock, cx| {
 2886                dock.set_open(false, window, cx);
 2887            });
 2888            return true;
 2889        }
 2890        false
 2891    }
 2892
 2893    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2894        for dock in self.all_docks() {
 2895            dock.update(cx, |dock, cx| {
 2896                dock.set_open(false, window, cx);
 2897            });
 2898        }
 2899
 2900        cx.focus_self(window);
 2901        cx.notify();
 2902        self.serialize_workspace(window, cx);
 2903    }
 2904
 2905    /// Transfer focus to the panel of the given type.
 2906    pub fn focus_panel<T: Panel>(
 2907        &mut self,
 2908        window: &mut Window,
 2909        cx: &mut Context<Self>,
 2910    ) -> Option<Entity<T>> {
 2911        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 2912        panel.to_any().downcast().ok()
 2913    }
 2914
 2915    /// Focus the panel of the given type if it isn't already focused. If it is
 2916    /// already focused, then transfer focus back to the workspace center.
 2917    pub fn toggle_panel_focus<T: Panel>(
 2918        &mut self,
 2919        window: &mut Window,
 2920        cx: &mut Context<Self>,
 2921    ) -> bool {
 2922        let mut did_focus_panel = false;
 2923        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 2924            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 2925            did_focus_panel
 2926        });
 2927        did_focus_panel
 2928    }
 2929
 2930    pub fn activate_panel_for_proto_id(
 2931        &mut self,
 2932        panel_id: PanelId,
 2933        window: &mut Window,
 2934        cx: &mut Context<Self>,
 2935    ) -> Option<Arc<dyn PanelHandle>> {
 2936        let mut panel = None;
 2937        for dock in self.all_docks() {
 2938            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 2939                panel = dock.update(cx, |dock, cx| {
 2940                    dock.activate_panel(panel_index, window, cx);
 2941                    dock.set_open(true, window, cx);
 2942                    dock.active_panel().cloned()
 2943                });
 2944                break;
 2945            }
 2946        }
 2947
 2948        if panel.is_some() {
 2949            cx.notify();
 2950            self.serialize_workspace(window, cx);
 2951        }
 2952
 2953        panel
 2954    }
 2955
 2956    /// Focus or unfocus the given panel type, depending on the given callback.
 2957    fn focus_or_unfocus_panel<T: Panel>(
 2958        &mut self,
 2959        window: &mut Window,
 2960        cx: &mut Context<Self>,
 2961        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 2962    ) -> Option<Arc<dyn PanelHandle>> {
 2963        let mut result_panel = None;
 2964        let mut serialize = false;
 2965        for dock in self.all_docks() {
 2966            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 2967                let mut focus_center = false;
 2968                let panel = dock.update(cx, |dock, cx| {
 2969                    dock.activate_panel(panel_index, window, cx);
 2970
 2971                    let panel = dock.active_panel().cloned();
 2972                    if let Some(panel) = panel.as_ref() {
 2973                        if should_focus(&**panel, window, cx) {
 2974                            dock.set_open(true, window, cx);
 2975                            panel.panel_focus_handle(cx).focus(window);
 2976                        } else {
 2977                            focus_center = true;
 2978                        }
 2979                    }
 2980                    panel
 2981                });
 2982
 2983                if focus_center {
 2984                    self.active_pane
 2985                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 2986                }
 2987
 2988                result_panel = panel;
 2989                serialize = true;
 2990                break;
 2991            }
 2992        }
 2993
 2994        if serialize {
 2995            self.serialize_workspace(window, cx);
 2996        }
 2997
 2998        cx.notify();
 2999        result_panel
 3000    }
 3001
 3002    /// Open the panel of the given type
 3003    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3004        for dock in self.all_docks() {
 3005            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3006                dock.update(cx, |dock, cx| {
 3007                    dock.activate_panel(panel_index, window, cx);
 3008                    dock.set_open(true, window, cx);
 3009                });
 3010            }
 3011        }
 3012    }
 3013
 3014    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3015        self.all_docks()
 3016            .iter()
 3017            .find_map(|dock| dock.read(cx).panel::<T>())
 3018    }
 3019
 3020    fn dismiss_zoomed_items_to_reveal(
 3021        &mut self,
 3022        dock_to_reveal: Option<DockPosition>,
 3023        window: &mut Window,
 3024        cx: &mut Context<Self>,
 3025    ) {
 3026        // If a center pane is zoomed, unzoom it.
 3027        for pane in &self.panes {
 3028            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3029                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3030            }
 3031        }
 3032
 3033        // If another dock is zoomed, hide it.
 3034        let mut focus_center = false;
 3035        for dock in self.all_docks() {
 3036            dock.update(cx, |dock, cx| {
 3037                if Some(dock.position()) != dock_to_reveal {
 3038                    if let Some(panel) = dock.active_panel() {
 3039                        if panel.is_zoomed(window, cx) {
 3040                            focus_center |=
 3041                                panel.panel_focus_handle(cx).contains_focused(window, cx);
 3042                            dock.set_open(false, window, cx);
 3043                        }
 3044                    }
 3045                }
 3046            });
 3047        }
 3048
 3049        if focus_center {
 3050            self.active_pane
 3051                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3052        }
 3053
 3054        if self.zoomed_position != dock_to_reveal {
 3055            self.zoomed = None;
 3056            self.zoomed_position = None;
 3057            cx.emit(Event::ZoomChanged);
 3058        }
 3059
 3060        cx.notify();
 3061    }
 3062
 3063    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3064        let pane = cx.new(|cx| {
 3065            let mut pane = Pane::new(
 3066                self.weak_handle(),
 3067                self.project.clone(),
 3068                self.pane_history_timestamp.clone(),
 3069                None,
 3070                NewFile.boxed_clone(),
 3071                window,
 3072                cx,
 3073            );
 3074            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3075            pane
 3076        });
 3077        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3078            .detach();
 3079        self.panes.push(pane.clone());
 3080
 3081        window.focus(&pane.focus_handle(cx));
 3082
 3083        cx.emit(Event::PaneAdded(pane.clone()));
 3084        pane
 3085    }
 3086
 3087    pub fn add_item_to_center(
 3088        &mut self,
 3089        item: Box<dyn ItemHandle>,
 3090        window: &mut Window,
 3091        cx: &mut Context<Self>,
 3092    ) -> bool {
 3093        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3094            if let Some(center_pane) = center_pane.upgrade() {
 3095                center_pane.update(cx, |pane, cx| {
 3096                    pane.add_item(item, true, true, None, window, cx)
 3097                });
 3098                true
 3099            } else {
 3100                false
 3101            }
 3102        } else {
 3103            false
 3104        }
 3105    }
 3106
 3107    pub fn add_item_to_active_pane(
 3108        &mut self,
 3109        item: Box<dyn ItemHandle>,
 3110        destination_index: Option<usize>,
 3111        focus_item: bool,
 3112        window: &mut Window,
 3113        cx: &mut App,
 3114    ) {
 3115        self.add_item(
 3116            self.active_pane.clone(),
 3117            item,
 3118            destination_index,
 3119            false,
 3120            focus_item,
 3121            window,
 3122            cx,
 3123        )
 3124    }
 3125
 3126    pub fn add_item(
 3127        &mut self,
 3128        pane: Entity<Pane>,
 3129        item: Box<dyn ItemHandle>,
 3130        destination_index: Option<usize>,
 3131        activate_pane: bool,
 3132        focus_item: bool,
 3133        window: &mut Window,
 3134        cx: &mut App,
 3135    ) {
 3136        if let Some(text) = item.telemetry_event_text(cx) {
 3137            telemetry::event!(text);
 3138        }
 3139
 3140        pane.update(cx, |pane, cx| {
 3141            pane.add_item(
 3142                item,
 3143                activate_pane,
 3144                focus_item,
 3145                destination_index,
 3146                window,
 3147                cx,
 3148            )
 3149        });
 3150    }
 3151
 3152    pub fn split_item(
 3153        &mut self,
 3154        split_direction: SplitDirection,
 3155        item: Box<dyn ItemHandle>,
 3156        window: &mut Window,
 3157        cx: &mut Context<Self>,
 3158    ) {
 3159        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3160        self.add_item(new_pane, item, None, true, true, window, cx);
 3161    }
 3162
 3163    pub fn open_abs_path(
 3164        &mut self,
 3165        abs_path: PathBuf,
 3166        options: OpenOptions,
 3167        window: &mut Window,
 3168        cx: &mut Context<Self>,
 3169    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3170        cx.spawn_in(window, async move |workspace, cx| {
 3171            let open_paths_task_result = workspace
 3172                .update_in(cx, |workspace, window, cx| {
 3173                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3174                })
 3175                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3176                .await;
 3177            anyhow::ensure!(
 3178                open_paths_task_result.len() == 1,
 3179                "open abs path {abs_path:?} task returned incorrect number of results"
 3180            );
 3181            match open_paths_task_result
 3182                .into_iter()
 3183                .next()
 3184                .expect("ensured single task result")
 3185            {
 3186                Some(open_result) => {
 3187                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3188                }
 3189                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3190            }
 3191        })
 3192    }
 3193
 3194    pub fn split_abs_path(
 3195        &mut self,
 3196        abs_path: PathBuf,
 3197        visible: bool,
 3198        window: &mut Window,
 3199        cx: &mut Context<Self>,
 3200    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3201        let project_path_task =
 3202            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3203        cx.spawn_in(window, async move |this, cx| {
 3204            let (_, path) = project_path_task.await?;
 3205            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3206                .await
 3207        })
 3208    }
 3209
 3210    pub fn open_path(
 3211        &mut self,
 3212        path: impl Into<ProjectPath>,
 3213        pane: Option<WeakEntity<Pane>>,
 3214        focus_item: bool,
 3215        window: &mut Window,
 3216        cx: &mut App,
 3217    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3218        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3219    }
 3220
 3221    pub fn open_path_preview(
 3222        &mut self,
 3223        path: impl Into<ProjectPath>,
 3224        pane: Option<WeakEntity<Pane>>,
 3225        focus_item: bool,
 3226        allow_preview: bool,
 3227        activate: bool,
 3228        window: &mut Window,
 3229        cx: &mut App,
 3230    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3231        let pane = pane.unwrap_or_else(|| {
 3232            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3233                self.panes
 3234                    .first()
 3235                    .expect("There must be an active pane")
 3236                    .downgrade()
 3237            })
 3238        });
 3239
 3240        let project_path = path.into();
 3241        let task = self.load_path(project_path.clone(), window, cx);
 3242        window.spawn(cx, async move |cx| {
 3243            let (project_entry_id, build_item) = task.await?;
 3244            let result = pane.update_in(cx, |pane, window, cx| {
 3245                pane.open_item(
 3246                    project_entry_id,
 3247                    project_path,
 3248                    focus_item,
 3249                    allow_preview,
 3250                    activate,
 3251                    None,
 3252                    window,
 3253                    cx,
 3254                    build_item,
 3255                )
 3256            });
 3257            result
 3258        })
 3259    }
 3260
 3261    pub fn split_path(
 3262        &mut self,
 3263        path: impl Into<ProjectPath>,
 3264        window: &mut Window,
 3265        cx: &mut Context<Self>,
 3266    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3267        self.split_path_preview(path, false, None, window, cx)
 3268    }
 3269
 3270    pub fn split_path_preview(
 3271        &mut self,
 3272        path: impl Into<ProjectPath>,
 3273        allow_preview: bool,
 3274        split_direction: Option<SplitDirection>,
 3275        window: &mut Window,
 3276        cx: &mut Context<Self>,
 3277    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3278        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3279            self.panes
 3280                .first()
 3281                .expect("There must be an active pane")
 3282                .downgrade()
 3283        });
 3284
 3285        if let Member::Pane(center_pane) = &self.center.root {
 3286            if center_pane.read(cx).items_len() == 0 {
 3287                return self.open_path(path, Some(pane), true, window, cx);
 3288            }
 3289        }
 3290
 3291        let project_path = path.into();
 3292        let task = self.load_path(project_path.clone(), window, cx);
 3293        cx.spawn_in(window, async move |this, cx| {
 3294            let (project_entry_id, build_item) = task.await?;
 3295            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3296                let pane = pane.upgrade()?;
 3297                let new_pane = this.split_pane(
 3298                    pane,
 3299                    split_direction.unwrap_or(SplitDirection::Right),
 3300                    window,
 3301                    cx,
 3302                );
 3303                new_pane.update(cx, |new_pane, cx| {
 3304                    Some(new_pane.open_item(
 3305                        project_entry_id,
 3306                        project_path,
 3307                        true,
 3308                        allow_preview,
 3309                        true,
 3310                        None,
 3311                        window,
 3312                        cx,
 3313                        build_item,
 3314                    ))
 3315                })
 3316            })
 3317            .map(|option| option.context("pane was dropped"))?
 3318        })
 3319    }
 3320
 3321    fn load_path(
 3322        &mut self,
 3323        path: ProjectPath,
 3324        window: &mut Window,
 3325        cx: &mut App,
 3326    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3327        let project = self.project().clone();
 3328        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3329        registry.open_path(&project, &path, window, cx)
 3330    }
 3331
 3332    pub fn find_project_item<T>(
 3333        &self,
 3334        pane: &Entity<Pane>,
 3335        project_item: &Entity<T::Item>,
 3336        cx: &App,
 3337    ) -> Option<Entity<T>>
 3338    where
 3339        T: ProjectItem,
 3340    {
 3341        use project::ProjectItem as _;
 3342        let project_item = project_item.read(cx);
 3343        let entry_id = project_item.entry_id(cx);
 3344        let project_path = project_item.project_path(cx);
 3345
 3346        let mut item = None;
 3347        if let Some(entry_id) = entry_id {
 3348            item = pane.read(cx).item_for_entry(entry_id, cx);
 3349        }
 3350        if item.is_none() {
 3351            if let Some(project_path) = project_path {
 3352                item = pane.read(cx).item_for_path(project_path, cx);
 3353            }
 3354        }
 3355
 3356        item.and_then(|item| item.downcast::<T>())
 3357    }
 3358
 3359    pub fn is_project_item_open<T>(
 3360        &self,
 3361        pane: &Entity<Pane>,
 3362        project_item: &Entity<T::Item>,
 3363        cx: &App,
 3364    ) -> bool
 3365    where
 3366        T: ProjectItem,
 3367    {
 3368        self.find_project_item::<T>(pane, project_item, cx)
 3369            .is_some()
 3370    }
 3371
 3372    pub fn open_project_item<T>(
 3373        &mut self,
 3374        pane: Entity<Pane>,
 3375        project_item: Entity<T::Item>,
 3376        activate_pane: bool,
 3377        focus_item: bool,
 3378        window: &mut Window,
 3379        cx: &mut Context<Self>,
 3380    ) -> Entity<T>
 3381    where
 3382        T: ProjectItem,
 3383    {
 3384        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3385            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3386            return item;
 3387        }
 3388
 3389        let item = pane.update(cx, |pane, cx| {
 3390            cx.new(|cx| {
 3391                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3392            })
 3393        });
 3394        let item_id = item.item_id();
 3395        let mut destination_index = None;
 3396        pane.update(cx, |pane, cx| {
 3397            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 3398                if let Some(preview_item_id) = pane.preview_item_id() {
 3399                    if preview_item_id != item_id {
 3400                        destination_index = pane.close_current_preview_item(window, cx);
 3401                    }
 3402                }
 3403            }
 3404            pane.set_preview_item_id(Some(item.item_id()), cx)
 3405        });
 3406
 3407        self.add_item(
 3408            pane,
 3409            Box::new(item.clone()),
 3410            destination_index,
 3411            activate_pane,
 3412            focus_item,
 3413            window,
 3414            cx,
 3415        );
 3416        item
 3417    }
 3418
 3419    pub fn open_shared_screen(
 3420        &mut self,
 3421        peer_id: PeerId,
 3422        window: &mut Window,
 3423        cx: &mut Context<Self>,
 3424    ) {
 3425        if let Some(shared_screen) =
 3426            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 3427        {
 3428            self.active_pane.update(cx, |pane, cx| {
 3429                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 3430            });
 3431        }
 3432    }
 3433
 3434    pub fn activate_item(
 3435        &mut self,
 3436        item: &dyn ItemHandle,
 3437        activate_pane: bool,
 3438        focus_item: bool,
 3439        window: &mut Window,
 3440        cx: &mut App,
 3441    ) -> bool {
 3442        let result = self.panes.iter().find_map(|pane| {
 3443            pane.read(cx)
 3444                .index_for_item(item)
 3445                .map(|ix| (pane.clone(), ix))
 3446        });
 3447        if let Some((pane, ix)) = result {
 3448            pane.update(cx, |pane, cx| {
 3449                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 3450            });
 3451            true
 3452        } else {
 3453            false
 3454        }
 3455    }
 3456
 3457    fn activate_pane_at_index(
 3458        &mut self,
 3459        action: &ActivatePane,
 3460        window: &mut Window,
 3461        cx: &mut Context<Self>,
 3462    ) {
 3463        let panes = self.center.panes();
 3464        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 3465            window.focus(&pane.focus_handle(cx));
 3466        } else {
 3467            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx);
 3468        }
 3469    }
 3470
 3471    fn move_item_to_pane_at_index(
 3472        &mut self,
 3473        action: &MoveItemToPane,
 3474        window: &mut Window,
 3475        cx: &mut Context<Self>,
 3476    ) {
 3477        let panes = self.center.panes();
 3478        let destination = match panes.get(action.destination) {
 3479            Some(&destination) => destination.clone(),
 3480            None => {
 3481                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3482                    return;
 3483                }
 3484                let direction = SplitDirection::Right;
 3485                let split_off_pane = self
 3486                    .find_pane_in_direction(direction, cx)
 3487                    .unwrap_or_else(|| self.active_pane.clone());
 3488                let new_pane = self.add_pane(window, cx);
 3489                if self
 3490                    .center
 3491                    .split(&split_off_pane, &new_pane, direction)
 3492                    .log_err()
 3493                    .is_none()
 3494                {
 3495                    return;
 3496                };
 3497                new_pane
 3498            }
 3499        };
 3500
 3501        if action.clone {
 3502            clone_active_item(
 3503                self.database_id(),
 3504                &self.active_pane,
 3505                &destination,
 3506                action.focus,
 3507                window,
 3508                cx,
 3509            )
 3510        } else {
 3511            move_active_item(
 3512                &self.active_pane,
 3513                &destination,
 3514                action.focus,
 3515                true,
 3516                window,
 3517                cx,
 3518            )
 3519        }
 3520    }
 3521
 3522    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3523        let panes = self.center.panes();
 3524        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3525            let next_ix = (ix + 1) % panes.len();
 3526            let next_pane = panes[next_ix].clone();
 3527            window.focus(&next_pane.focus_handle(cx));
 3528        }
 3529    }
 3530
 3531    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3532        let panes = self.center.panes();
 3533        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3534            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3535            let prev_pane = panes[prev_ix].clone();
 3536            window.focus(&prev_pane.focus_handle(cx));
 3537        }
 3538    }
 3539
 3540    pub fn activate_pane_in_direction(
 3541        &mut self,
 3542        direction: SplitDirection,
 3543        window: &mut Window,
 3544        cx: &mut App,
 3545    ) {
 3546        use ActivateInDirectionTarget as Target;
 3547        enum Origin {
 3548            LeftDock,
 3549            RightDock,
 3550            BottomDock,
 3551            Center,
 3552        }
 3553
 3554        let origin: Origin = [
 3555            (&self.left_dock, Origin::LeftDock),
 3556            (&self.right_dock, Origin::RightDock),
 3557            (&self.bottom_dock, Origin::BottomDock),
 3558        ]
 3559        .into_iter()
 3560        .find_map(|(dock, origin)| {
 3561            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 3562                Some(origin)
 3563            } else {
 3564                None
 3565            }
 3566        })
 3567        .unwrap_or(Origin::Center);
 3568
 3569        let get_last_active_pane = || {
 3570            let pane = self
 3571                .last_active_center_pane
 3572                .clone()
 3573                .unwrap_or_else(|| {
 3574                    self.panes
 3575                        .first()
 3576                        .expect("There must be an active pane")
 3577                        .downgrade()
 3578                })
 3579                .upgrade()?;
 3580            (pane.read(cx).items_len() != 0).then_some(pane)
 3581        };
 3582
 3583        let try_dock =
 3584            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 3585
 3586        let target = match (origin, direction) {
 3587            // We're in the center, so we first try to go to a different pane,
 3588            // otherwise try to go to a dock.
 3589            (Origin::Center, direction) => {
 3590                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 3591                    Some(Target::Pane(pane))
 3592                } else {
 3593                    match direction {
 3594                        SplitDirection::Up => None,
 3595                        SplitDirection::Down => try_dock(&self.bottom_dock),
 3596                        SplitDirection::Left => try_dock(&self.left_dock),
 3597                        SplitDirection::Right => try_dock(&self.right_dock),
 3598                    }
 3599                }
 3600            }
 3601
 3602            (Origin::LeftDock, SplitDirection::Right) => {
 3603                if let Some(last_active_pane) = get_last_active_pane() {
 3604                    Some(Target::Pane(last_active_pane))
 3605                } else {
 3606                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 3607                }
 3608            }
 3609
 3610            (Origin::LeftDock, SplitDirection::Down)
 3611            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 3612
 3613            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 3614            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 3615            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 3616
 3617            (Origin::RightDock, SplitDirection::Left) => {
 3618                if let Some(last_active_pane) = get_last_active_pane() {
 3619                    Some(Target::Pane(last_active_pane))
 3620                } else {
 3621                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 3622                }
 3623            }
 3624
 3625            _ => None,
 3626        };
 3627
 3628        match target {
 3629            Some(ActivateInDirectionTarget::Pane(pane)) => {
 3630                let pane = pane.read(cx);
 3631                if let Some(item) = pane.active_item() {
 3632                    item.item_focus_handle(cx).focus(window);
 3633                } else {
 3634                    log::error!(
 3635                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 3636                    );
 3637                }
 3638            }
 3639            Some(ActivateInDirectionTarget::Dock(dock)) => {
 3640                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 3641                window.defer(cx, move |window, cx| {
 3642                    let dock = dock.read(cx);
 3643                    if let Some(panel) = dock.active_panel() {
 3644                        panel.panel_focus_handle(cx).focus(window);
 3645                    } else {
 3646                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 3647                    }
 3648                })
 3649            }
 3650            None => {}
 3651        }
 3652    }
 3653
 3654    pub fn move_item_to_pane_in_direction(
 3655        &mut self,
 3656        action: &MoveItemToPaneInDirection,
 3657        window: &mut Window,
 3658        cx: &mut Context<Self>,
 3659    ) {
 3660        let destination = match self.find_pane_in_direction(action.direction, cx) {
 3661            Some(destination) => destination,
 3662            None => {
 3663                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3664                    return;
 3665                }
 3666                let new_pane = self.add_pane(window, cx);
 3667                if self
 3668                    .center
 3669                    .split(&self.active_pane, &new_pane, action.direction)
 3670                    .log_err()
 3671                    .is_none()
 3672                {
 3673                    return;
 3674                };
 3675                new_pane
 3676            }
 3677        };
 3678
 3679        if action.clone {
 3680            clone_active_item(
 3681                self.database_id(),
 3682                &self.active_pane,
 3683                &destination,
 3684                action.focus,
 3685                window,
 3686                cx,
 3687            )
 3688        } else {
 3689            move_active_item(
 3690                &self.active_pane,
 3691                &destination,
 3692                action.focus,
 3693                true,
 3694                window,
 3695                cx,
 3696            );
 3697        }
 3698    }
 3699
 3700    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 3701        self.center.bounding_box_for_pane(pane)
 3702    }
 3703
 3704    pub fn find_pane_in_direction(
 3705        &mut self,
 3706        direction: SplitDirection,
 3707        cx: &App,
 3708    ) -> Option<Entity<Pane>> {
 3709        self.center
 3710            .find_pane_in_direction(&self.active_pane, direction, cx)
 3711            .cloned()
 3712    }
 3713
 3714    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 3715        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 3716            self.center.swap(&self.active_pane, &to);
 3717            cx.notify();
 3718        }
 3719    }
 3720
 3721    pub fn resize_pane(
 3722        &mut self,
 3723        axis: gpui::Axis,
 3724        amount: Pixels,
 3725        window: &mut Window,
 3726        cx: &mut Context<Self>,
 3727    ) {
 3728        let docks = self.all_docks();
 3729        let active_dock = docks
 3730            .into_iter()
 3731            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3732
 3733        if let Some(dock) = active_dock {
 3734            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 3735                return;
 3736            };
 3737            match dock.read(cx).position() {
 3738                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 3739                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 3740                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 3741            }
 3742        } else {
 3743            self.center
 3744                .resize(&self.active_pane, axis, amount, &self.bounds);
 3745        }
 3746        cx.notify();
 3747    }
 3748
 3749    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 3750        self.center.reset_pane_sizes();
 3751        cx.notify();
 3752    }
 3753
 3754    fn handle_pane_focused(
 3755        &mut self,
 3756        pane: Entity<Pane>,
 3757        window: &mut Window,
 3758        cx: &mut Context<Self>,
 3759    ) {
 3760        // This is explicitly hoisted out of the following check for pane identity as
 3761        // terminal panel panes are not registered as a center panes.
 3762        self.status_bar.update(cx, |status_bar, cx| {
 3763            status_bar.set_active_pane(&pane, window, cx);
 3764        });
 3765        if self.active_pane != pane {
 3766            self.set_active_pane(&pane, window, cx);
 3767        }
 3768
 3769        if self.last_active_center_pane.is_none() {
 3770            self.last_active_center_pane = Some(pane.downgrade());
 3771        }
 3772
 3773        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 3774        if pane.read(cx).is_zoomed() {
 3775            self.zoomed = Some(pane.downgrade().into());
 3776        } else {
 3777            self.zoomed = None;
 3778        }
 3779        self.zoomed_position = None;
 3780        cx.emit(Event::ZoomChanged);
 3781        self.update_active_view_for_followers(window, cx);
 3782        pane.update(cx, |pane, _| {
 3783            pane.track_alternate_file_items();
 3784        });
 3785
 3786        cx.notify();
 3787    }
 3788
 3789    fn set_active_pane(
 3790        &mut self,
 3791        pane: &Entity<Pane>,
 3792        window: &mut Window,
 3793        cx: &mut Context<Self>,
 3794    ) {
 3795        self.active_pane = pane.clone();
 3796        self.active_item_path_changed(window, cx);
 3797        self.last_active_center_pane = Some(pane.downgrade());
 3798    }
 3799
 3800    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3801        self.update_active_view_for_followers(window, cx);
 3802    }
 3803
 3804    fn handle_pane_event(
 3805        &mut self,
 3806        pane: &Entity<Pane>,
 3807        event: &pane::Event,
 3808        window: &mut Window,
 3809        cx: &mut Context<Self>,
 3810    ) {
 3811        let mut serialize_workspace = true;
 3812        match event {
 3813            pane::Event::AddItem { item } => {
 3814                item.added_to_pane(self, pane.clone(), window, cx);
 3815                cx.emit(Event::ItemAdded {
 3816                    item: item.boxed_clone(),
 3817                });
 3818            }
 3819            pane::Event::Split(direction) => {
 3820                self.split_and_clone(pane.clone(), *direction, window, cx);
 3821            }
 3822            pane::Event::JoinIntoNext => {
 3823                self.join_pane_into_next(pane.clone(), window, cx);
 3824            }
 3825            pane::Event::JoinAll => {
 3826                self.join_all_panes(window, cx);
 3827            }
 3828            pane::Event::Remove { focus_on_pane } => {
 3829                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 3830            }
 3831            pane::Event::ActivateItem {
 3832                local,
 3833                focus_changed,
 3834            } => {
 3835                cx.on_next_frame(window, |_, window, _| {
 3836                    window.invalidate_character_coordinates();
 3837                });
 3838
 3839                pane.update(cx, |pane, _| {
 3840                    pane.track_alternate_file_items();
 3841                });
 3842                if *local {
 3843                    self.unfollow_in_pane(&pane, window, cx);
 3844                }
 3845                if pane == self.active_pane() {
 3846                    self.active_item_path_changed(window, cx);
 3847                    self.update_active_view_for_followers(window, cx);
 3848                }
 3849                serialize_workspace = *focus_changed || pane != self.active_pane();
 3850            }
 3851            pane::Event::UserSavedItem { item, save_intent } => {
 3852                cx.emit(Event::UserSavedItem {
 3853                    pane: pane.downgrade(),
 3854                    item: item.boxed_clone(),
 3855                    save_intent: *save_intent,
 3856                });
 3857                serialize_workspace = false;
 3858            }
 3859            pane::Event::ChangeItemTitle => {
 3860                if *pane == self.active_pane {
 3861                    self.active_item_path_changed(window, cx);
 3862                }
 3863                serialize_workspace = false;
 3864            }
 3865            pane::Event::RemoveItem { .. } => {}
 3866            pane::Event::RemovedItem { item } => {
 3867                cx.emit(Event::ActiveItemChanged);
 3868                self.update_window_edited(window, cx);
 3869                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id()) {
 3870                    if entry.get().entity_id() == pane.entity_id() {
 3871                        entry.remove();
 3872                    }
 3873                }
 3874            }
 3875            pane::Event::Focus => {
 3876                cx.on_next_frame(window, |_, window, _| {
 3877                    window.invalidate_character_coordinates();
 3878                });
 3879                self.handle_pane_focused(pane.clone(), window, cx);
 3880            }
 3881            pane::Event::ZoomIn => {
 3882                if *pane == self.active_pane {
 3883                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 3884                    if pane.read(cx).has_focus(window, cx) {
 3885                        self.zoomed = Some(pane.downgrade().into());
 3886                        self.zoomed_position = None;
 3887                        cx.emit(Event::ZoomChanged);
 3888                    }
 3889                    cx.notify();
 3890                }
 3891            }
 3892            pane::Event::ZoomOut => {
 3893                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3894                if self.zoomed_position.is_none() {
 3895                    self.zoomed = None;
 3896                    cx.emit(Event::ZoomChanged);
 3897                }
 3898                cx.notify();
 3899            }
 3900            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 3901        }
 3902
 3903        if serialize_workspace {
 3904            self.serialize_workspace(window, cx);
 3905        }
 3906    }
 3907
 3908    pub fn unfollow_in_pane(
 3909        &mut self,
 3910        pane: &Entity<Pane>,
 3911        window: &mut Window,
 3912        cx: &mut Context<Workspace>,
 3913    ) -> Option<CollaboratorId> {
 3914        let leader_id = self.leader_for_pane(pane)?;
 3915        self.unfollow(leader_id, window, cx);
 3916        Some(leader_id)
 3917    }
 3918
 3919    pub fn split_pane(
 3920        &mut self,
 3921        pane_to_split: Entity<Pane>,
 3922        split_direction: SplitDirection,
 3923        window: &mut Window,
 3924        cx: &mut Context<Self>,
 3925    ) -> Entity<Pane> {
 3926        let new_pane = self.add_pane(window, cx);
 3927        self.center
 3928            .split(&pane_to_split, &new_pane, split_direction)
 3929            .unwrap();
 3930        cx.notify();
 3931        new_pane
 3932    }
 3933
 3934    pub fn split_and_clone(
 3935        &mut self,
 3936        pane: Entity<Pane>,
 3937        direction: SplitDirection,
 3938        window: &mut Window,
 3939        cx: &mut Context<Self>,
 3940    ) -> Option<Entity<Pane>> {
 3941        let item = pane.read(cx).active_item()?;
 3942        let maybe_pane_handle =
 3943            if let Some(clone) = item.clone_on_split(self.database_id(), window, cx) {
 3944                let new_pane = self.add_pane(window, cx);
 3945                new_pane.update(cx, |pane, cx| {
 3946                    pane.add_item(clone, true, true, None, window, cx)
 3947                });
 3948                self.center.split(&pane, &new_pane, direction).unwrap();
 3949                Some(new_pane)
 3950            } else {
 3951                None
 3952            };
 3953        cx.notify();
 3954        maybe_pane_handle
 3955    }
 3956
 3957    pub fn split_pane_with_item(
 3958        &mut self,
 3959        pane_to_split: WeakEntity<Pane>,
 3960        split_direction: SplitDirection,
 3961        from: WeakEntity<Pane>,
 3962        item_id_to_move: EntityId,
 3963        window: &mut Window,
 3964        cx: &mut Context<Self>,
 3965    ) {
 3966        let Some(pane_to_split) = pane_to_split.upgrade() else {
 3967            return;
 3968        };
 3969        let Some(from) = from.upgrade() else {
 3970            return;
 3971        };
 3972
 3973        let new_pane = self.add_pane(window, cx);
 3974        move_item(&from, &new_pane, item_id_to_move, 0, true, window, cx);
 3975        self.center
 3976            .split(&pane_to_split, &new_pane, split_direction)
 3977            .unwrap();
 3978        cx.notify();
 3979    }
 3980
 3981    pub fn split_pane_with_project_entry(
 3982        &mut self,
 3983        pane_to_split: WeakEntity<Pane>,
 3984        split_direction: SplitDirection,
 3985        project_entry: ProjectEntryId,
 3986        window: &mut Window,
 3987        cx: &mut Context<Self>,
 3988    ) -> Option<Task<Result<()>>> {
 3989        let pane_to_split = pane_to_split.upgrade()?;
 3990        let new_pane = self.add_pane(window, cx);
 3991        self.center
 3992            .split(&pane_to_split, &new_pane, split_direction)
 3993            .unwrap();
 3994
 3995        let path = self.project.read(cx).path_for_entry(project_entry, cx)?;
 3996        let task = self.open_path(path, Some(new_pane.downgrade()), true, window, cx);
 3997        Some(cx.foreground_executor().spawn(async move {
 3998            task.await?;
 3999            Ok(())
 4000        }))
 4001    }
 4002
 4003    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4004        let active_item = self.active_pane.read(cx).active_item();
 4005        for pane in &self.panes {
 4006            join_pane_into_active(&self.active_pane, pane, window, cx);
 4007        }
 4008        if let Some(active_item) = active_item {
 4009            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4010        }
 4011        cx.notify();
 4012    }
 4013
 4014    pub fn join_pane_into_next(
 4015        &mut self,
 4016        pane: Entity<Pane>,
 4017        window: &mut Window,
 4018        cx: &mut Context<Self>,
 4019    ) {
 4020        let next_pane = self
 4021            .find_pane_in_direction(SplitDirection::Right, cx)
 4022            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4023            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4024            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4025        let Some(next_pane) = next_pane else {
 4026            return;
 4027        };
 4028        move_all_items(&pane, &next_pane, window, cx);
 4029        cx.notify();
 4030    }
 4031
 4032    fn remove_pane(
 4033        &mut self,
 4034        pane: Entity<Pane>,
 4035        focus_on: Option<Entity<Pane>>,
 4036        window: &mut Window,
 4037        cx: &mut Context<Self>,
 4038    ) {
 4039        if self.center.remove(&pane).unwrap() {
 4040            self.force_remove_pane(&pane, &focus_on, window, cx);
 4041            self.unfollow_in_pane(&pane, window, cx);
 4042            self.last_leaders_by_pane.remove(&pane.downgrade());
 4043            for removed_item in pane.read(cx).items() {
 4044                self.panes_by_item.remove(&removed_item.item_id());
 4045            }
 4046
 4047            cx.notify();
 4048        } else {
 4049            self.active_item_path_changed(window, cx);
 4050        }
 4051        cx.emit(Event::PaneRemoved);
 4052    }
 4053
 4054    pub fn panes(&self) -> &[Entity<Pane>] {
 4055        &self.panes
 4056    }
 4057
 4058    pub fn active_pane(&self) -> &Entity<Pane> {
 4059        &self.active_pane
 4060    }
 4061
 4062    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4063        for dock in self.all_docks() {
 4064            if dock.focus_handle(cx).contains_focused(window, cx) {
 4065                if let Some(pane) = dock
 4066                    .read(cx)
 4067                    .active_panel()
 4068                    .and_then(|panel| panel.pane(cx))
 4069                {
 4070                    return pane;
 4071                }
 4072            }
 4073        }
 4074        self.active_pane().clone()
 4075    }
 4076
 4077    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4078        self.find_pane_in_direction(SplitDirection::Right, cx)
 4079            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4080            .unwrap_or_else(|| {
 4081                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4082            })
 4083            .clone()
 4084    }
 4085
 4086    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4087        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4088        weak_pane.upgrade()
 4089    }
 4090
 4091    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4092        self.follower_states.retain(|leader_id, state| {
 4093            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4094                for item in state.items_by_leader_view_id.values() {
 4095                    item.view.set_leader_id(None, window, cx);
 4096                }
 4097                false
 4098            } else {
 4099                true
 4100            }
 4101        });
 4102        cx.notify();
 4103    }
 4104
 4105    pub fn start_following(
 4106        &mut self,
 4107        leader_id: impl Into<CollaboratorId>,
 4108        window: &mut Window,
 4109        cx: &mut Context<Self>,
 4110    ) -> Option<Task<Result<()>>> {
 4111        let leader_id = leader_id.into();
 4112        let pane = self.active_pane().clone();
 4113
 4114        self.last_leaders_by_pane
 4115            .insert(pane.downgrade(), leader_id);
 4116        self.unfollow(leader_id, window, cx);
 4117        self.unfollow_in_pane(&pane, window, cx);
 4118        self.follower_states.insert(
 4119            leader_id,
 4120            FollowerState {
 4121                center_pane: pane.clone(),
 4122                dock_pane: None,
 4123                active_view_id: None,
 4124                items_by_leader_view_id: Default::default(),
 4125            },
 4126        );
 4127        cx.notify();
 4128
 4129        match leader_id {
 4130            CollaboratorId::PeerId(leader_peer_id) => {
 4131                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4132                let project_id = self.project.read(cx).remote_id();
 4133                let request = self.app_state.client.request(proto::Follow {
 4134                    room_id,
 4135                    project_id,
 4136                    leader_id: Some(leader_peer_id),
 4137                });
 4138
 4139                Some(cx.spawn_in(window, async move |this, cx| {
 4140                    let response = request.await?;
 4141                    this.update(cx, |this, _| {
 4142                        let state = this
 4143                            .follower_states
 4144                            .get_mut(&leader_id)
 4145                            .context("following interrupted")?;
 4146                        state.active_view_id = response
 4147                            .active_view
 4148                            .as_ref()
 4149                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4150                        anyhow::Ok(())
 4151                    })??;
 4152                    if let Some(view) = response.active_view {
 4153                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4154                    }
 4155                    this.update_in(cx, |this, window, cx| {
 4156                        this.leader_updated(leader_id, window, cx)
 4157                    })?;
 4158                    Ok(())
 4159                }))
 4160            }
 4161            CollaboratorId::Agent => {
 4162                self.leader_updated(leader_id, window, cx)?;
 4163                Some(Task::ready(Ok(())))
 4164            }
 4165        }
 4166    }
 4167
 4168    pub fn follow_next_collaborator(
 4169        &mut self,
 4170        _: &FollowNextCollaborator,
 4171        window: &mut Window,
 4172        cx: &mut Context<Self>,
 4173    ) {
 4174        let collaborators = self.project.read(cx).collaborators();
 4175        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4176            let mut collaborators = collaborators.keys().copied();
 4177            for peer_id in collaborators.by_ref() {
 4178                if CollaboratorId::PeerId(peer_id) == leader_id {
 4179                    break;
 4180                }
 4181            }
 4182            collaborators.next().map(CollaboratorId::PeerId)
 4183        } else if let Some(last_leader_id) =
 4184            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4185        {
 4186            match last_leader_id {
 4187                CollaboratorId::PeerId(peer_id) => {
 4188                    if collaborators.contains_key(peer_id) {
 4189                        Some(*last_leader_id)
 4190                    } else {
 4191                        None
 4192                    }
 4193                }
 4194                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4195            }
 4196        } else {
 4197            None
 4198        };
 4199
 4200        let pane = self.active_pane.clone();
 4201        let Some(leader_id) = next_leader_id.or_else(|| {
 4202            Some(CollaboratorId::PeerId(
 4203                collaborators.keys().copied().next()?,
 4204            ))
 4205        }) else {
 4206            return;
 4207        };
 4208        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4209            return;
 4210        }
 4211        if let Some(task) = self.start_following(leader_id, window, cx) {
 4212            task.detach_and_log_err(cx)
 4213        }
 4214    }
 4215
 4216    pub fn follow(
 4217        &mut self,
 4218        leader_id: impl Into<CollaboratorId>,
 4219        window: &mut Window,
 4220        cx: &mut Context<Self>,
 4221    ) {
 4222        let leader_id = leader_id.into();
 4223
 4224        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4225            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4226                return;
 4227            };
 4228            let room = room.read(cx);
 4229            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4230                return;
 4231            };
 4232
 4233            let project = self.project.read(cx);
 4234
 4235            let other_project_id = match remote_participant.location {
 4236                call::ParticipantLocation::External => None,
 4237                call::ParticipantLocation::UnsharedProject => None,
 4238                call::ParticipantLocation::SharedProject { project_id } => {
 4239                    if Some(project_id) == project.remote_id() {
 4240                        None
 4241                    } else {
 4242                        Some(project_id)
 4243                    }
 4244                }
 4245            };
 4246
 4247            // if they are active in another project, follow there.
 4248            if let Some(project_id) = other_project_id {
 4249                let app_state = self.app_state.clone();
 4250                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4251                    .detach_and_log_err(cx);
 4252            }
 4253        }
 4254
 4255        // if you're already following, find the right pane and focus it.
 4256        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4257            window.focus(&follower_state.pane().focus_handle(cx));
 4258
 4259            return;
 4260        }
 4261
 4262        // Otherwise, follow.
 4263        if let Some(task) = self.start_following(leader_id, window, cx) {
 4264            task.detach_and_log_err(cx)
 4265        }
 4266    }
 4267
 4268    pub fn unfollow(
 4269        &mut self,
 4270        leader_id: impl Into<CollaboratorId>,
 4271        window: &mut Window,
 4272        cx: &mut Context<Self>,
 4273    ) -> Option<()> {
 4274        cx.notify();
 4275
 4276        let leader_id = leader_id.into();
 4277        let state = self.follower_states.remove(&leader_id)?;
 4278        for (_, item) in state.items_by_leader_view_id {
 4279            item.view.set_leader_id(None, window, cx);
 4280        }
 4281
 4282        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4283            let project_id = self.project.read(cx).remote_id();
 4284            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4285            self.app_state
 4286                .client
 4287                .send(proto::Unfollow {
 4288                    room_id,
 4289                    project_id,
 4290                    leader_id: Some(leader_peer_id),
 4291                })
 4292                .log_err();
 4293        }
 4294
 4295        Some(())
 4296    }
 4297
 4298    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4299        self.follower_states.contains_key(&id.into())
 4300    }
 4301
 4302    fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4303        cx.emit(Event::ActiveItemChanged);
 4304        let active_entry = self.active_project_path(cx);
 4305        self.project
 4306            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 4307
 4308        self.update_window_title(window, cx);
 4309    }
 4310
 4311    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4312        let project = self.project().read(cx);
 4313        let mut title = String::new();
 4314
 4315        for (i, name) in project.worktree_root_names(cx).enumerate() {
 4316            if i > 0 {
 4317                title.push_str(", ");
 4318            }
 4319            title.push_str(name);
 4320        }
 4321
 4322        if title.is_empty() {
 4323            title = "empty project".to_string();
 4324        }
 4325
 4326        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4327            let filename = path
 4328                .path
 4329                .file_name()
 4330                .map(|s| s.to_string_lossy())
 4331                .or_else(|| {
 4332                    Some(Cow::Borrowed(
 4333                        project
 4334                            .worktree_for_id(path.worktree_id, cx)?
 4335                            .read(cx)
 4336                            .root_name(),
 4337                    ))
 4338                });
 4339
 4340            if let Some(filename) = filename {
 4341                title.push_str("");
 4342                title.push_str(filename.as_ref());
 4343            }
 4344        }
 4345
 4346        if project.is_via_collab() {
 4347            title.push_str("");
 4348        } else if project.is_shared() {
 4349            title.push_str("");
 4350        }
 4351
 4352        window.set_window_title(&title);
 4353    }
 4354
 4355    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4356        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4357        if is_edited != self.window_edited {
 4358            self.window_edited = is_edited;
 4359            window.set_window_edited(self.window_edited)
 4360        }
 4361    }
 4362
 4363    fn update_item_dirty_state(
 4364        &mut self,
 4365        item: &dyn ItemHandle,
 4366        window: &mut Window,
 4367        cx: &mut App,
 4368    ) {
 4369        let is_dirty = item.is_dirty(cx);
 4370        let item_id = item.item_id();
 4371        let was_dirty = self.dirty_items.contains_key(&item_id);
 4372        if is_dirty == was_dirty {
 4373            return;
 4374        }
 4375        if was_dirty {
 4376            self.dirty_items.remove(&item_id);
 4377            self.update_window_edited(window, cx);
 4378            return;
 4379        }
 4380        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4381            let s = item.on_release(
 4382                cx,
 4383                Box::new(move |cx| {
 4384                    window_handle
 4385                        .update(cx, |this, window, cx| {
 4386                            this.dirty_items.remove(&item_id);
 4387                            this.update_window_edited(window, cx)
 4388                        })
 4389                        .ok();
 4390                }),
 4391            );
 4392            self.dirty_items.insert(item_id, s);
 4393            self.update_window_edited(window, cx);
 4394        }
 4395    }
 4396
 4397    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4398        if self.notifications.is_empty() {
 4399            None
 4400        } else {
 4401            Some(
 4402                div()
 4403                    .absolute()
 4404                    .right_3()
 4405                    .bottom_3()
 4406                    .w_112()
 4407                    .h_full()
 4408                    .flex()
 4409                    .flex_col()
 4410                    .justify_end()
 4411                    .gap_2()
 4412                    .children(
 4413                        self.notifications
 4414                            .iter()
 4415                            .map(|(_, notification)| notification.clone().into_any()),
 4416                    ),
 4417            )
 4418        }
 4419    }
 4420
 4421    // RPC handlers
 4422
 4423    fn active_view_for_follower(
 4424        &self,
 4425        follower_project_id: Option<u64>,
 4426        window: &mut Window,
 4427        cx: &mut Context<Self>,
 4428    ) -> Option<proto::View> {
 4429        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4430        let item = item?;
 4431        let leader_id = self
 4432            .pane_for(&*item)
 4433            .and_then(|pane| self.leader_for_pane(&pane));
 4434        let leader_peer_id = match leader_id {
 4435            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4436            Some(CollaboratorId::Agent) | None => None,
 4437        };
 4438
 4439        let item_handle = item.to_followable_item_handle(cx)?;
 4440        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4441        let variant = item_handle.to_state_proto(window, cx)?;
 4442
 4443        if item_handle.is_project_item(window, cx)
 4444            && (follower_project_id.is_none()
 4445                || follower_project_id != self.project.read(cx).remote_id())
 4446        {
 4447            return None;
 4448        }
 4449
 4450        Some(proto::View {
 4451            id: id.to_proto(),
 4452            leader_id: leader_peer_id,
 4453            variant: Some(variant),
 4454            panel_id: panel_id.map(|id| id as i32),
 4455        })
 4456    }
 4457
 4458    fn handle_follow(
 4459        &mut self,
 4460        follower_project_id: Option<u64>,
 4461        window: &mut Window,
 4462        cx: &mut Context<Self>,
 4463    ) -> proto::FollowResponse {
 4464        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4465
 4466        cx.notify();
 4467        proto::FollowResponse {
 4468            // TODO: Remove after version 0.145.x stabilizes.
 4469            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4470            views: active_view.iter().cloned().collect(),
 4471            active_view,
 4472        }
 4473    }
 4474
 4475    fn handle_update_followers(
 4476        &mut self,
 4477        leader_id: PeerId,
 4478        message: proto::UpdateFollowers,
 4479        _window: &mut Window,
 4480        _cx: &mut Context<Self>,
 4481    ) {
 4482        self.leader_updates_tx
 4483            .unbounded_send((leader_id, message))
 4484            .ok();
 4485    }
 4486
 4487    async fn process_leader_update(
 4488        this: &WeakEntity<Self>,
 4489        leader_id: PeerId,
 4490        update: proto::UpdateFollowers,
 4491        cx: &mut AsyncWindowContext,
 4492    ) -> Result<()> {
 4493        match update.variant.context("invalid update")? {
 4494            proto::update_followers::Variant::CreateView(view) => {
 4495                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4496                let should_add_view = this.update(cx, |this, _| {
 4497                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4498                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4499                    } else {
 4500                        anyhow::Ok(false)
 4501                    }
 4502                })??;
 4503
 4504                if should_add_view {
 4505                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4506                }
 4507            }
 4508            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4509                let should_add_view = this.update(cx, |this, _| {
 4510                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4511                        state.active_view_id = update_active_view
 4512                            .view
 4513                            .as_ref()
 4514                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4515
 4516                        if state.active_view_id.is_some_and(|view_id| {
 4517                            !state.items_by_leader_view_id.contains_key(&view_id)
 4518                        }) {
 4519                            anyhow::Ok(true)
 4520                        } else {
 4521                            anyhow::Ok(false)
 4522                        }
 4523                    } else {
 4524                        anyhow::Ok(false)
 4525                    }
 4526                })??;
 4527
 4528                if should_add_view {
 4529                    if let Some(view) = update_active_view.view {
 4530                        Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4531                    }
 4532                }
 4533            }
 4534            proto::update_followers::Variant::UpdateView(update_view) => {
 4535                let variant = update_view.variant.context("missing update view variant")?;
 4536                let id = update_view.id.context("missing update view id")?;
 4537                let mut tasks = Vec::new();
 4538                this.update_in(cx, |this, window, cx| {
 4539                    let project = this.project.clone();
 4540                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 4541                        let view_id = ViewId::from_proto(id.clone())?;
 4542                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 4543                            tasks.push(item.view.apply_update_proto(
 4544                                &project,
 4545                                variant.clone(),
 4546                                window,
 4547                                cx,
 4548                            ));
 4549                        }
 4550                    }
 4551                    anyhow::Ok(())
 4552                })??;
 4553                try_join_all(tasks).await.log_err();
 4554            }
 4555        }
 4556        this.update_in(cx, |this, window, cx| {
 4557            this.leader_updated(leader_id, window, cx)
 4558        })?;
 4559        Ok(())
 4560    }
 4561
 4562    async fn add_view_from_leader(
 4563        this: WeakEntity<Self>,
 4564        leader_id: PeerId,
 4565        view: &proto::View,
 4566        cx: &mut AsyncWindowContext,
 4567    ) -> Result<()> {
 4568        let this = this.upgrade().context("workspace dropped")?;
 4569
 4570        let Some(id) = view.id.clone() else {
 4571            anyhow::bail!("no id for view");
 4572        };
 4573        let id = ViewId::from_proto(id)?;
 4574        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 4575
 4576        let pane = this.update(cx, |this, _cx| {
 4577            let state = this
 4578                .follower_states
 4579                .get(&leader_id.into())
 4580                .context("stopped following")?;
 4581            anyhow::Ok(state.pane().clone())
 4582        })??;
 4583        let existing_item = pane.update_in(cx, |pane, window, cx| {
 4584            let client = this.read(cx).client().clone();
 4585            pane.items().find_map(|item| {
 4586                let item = item.to_followable_item_handle(cx)?;
 4587                if item.remote_id(&client, window, cx) == Some(id) {
 4588                    Some(item)
 4589                } else {
 4590                    None
 4591                }
 4592            })
 4593        })?;
 4594        let item = if let Some(existing_item) = existing_item {
 4595            existing_item
 4596        } else {
 4597            let variant = view.variant.clone();
 4598            anyhow::ensure!(variant.is_some(), "missing view variant");
 4599
 4600            let task = cx.update(|window, cx| {
 4601                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 4602            })?;
 4603
 4604            let Some(task) = task else {
 4605                anyhow::bail!(
 4606                    "failed to construct view from leader (maybe from a different version of zed?)"
 4607                );
 4608            };
 4609
 4610            let mut new_item = task.await?;
 4611            pane.update_in(cx, |pane, window, cx| {
 4612                let mut item_to_remove = None;
 4613                for (ix, item) in pane.items().enumerate() {
 4614                    if let Some(item) = item.to_followable_item_handle(cx) {
 4615                        match new_item.dedup(item.as_ref(), window, cx) {
 4616                            Some(item::Dedup::KeepExisting) => {
 4617                                new_item =
 4618                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 4619                                break;
 4620                            }
 4621                            Some(item::Dedup::ReplaceExisting) => {
 4622                                item_to_remove = Some((ix, item.item_id()));
 4623                                break;
 4624                            }
 4625                            None => {}
 4626                        }
 4627                    }
 4628                }
 4629
 4630                if let Some((ix, id)) = item_to_remove {
 4631                    pane.remove_item(id, false, false, window, cx);
 4632                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 4633                }
 4634            })?;
 4635
 4636            new_item
 4637        };
 4638
 4639        this.update_in(cx, |this, window, cx| {
 4640            let state = this.follower_states.get_mut(&leader_id.into())?;
 4641            item.set_leader_id(Some(leader_id.into()), window, cx);
 4642            state.items_by_leader_view_id.insert(
 4643                id,
 4644                FollowerView {
 4645                    view: item,
 4646                    location: panel_id,
 4647                },
 4648            );
 4649
 4650            Some(())
 4651        })?;
 4652
 4653        Ok(())
 4654    }
 4655
 4656    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4657        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 4658            return;
 4659        };
 4660
 4661        if let Some(agent_location) = self.project.read(cx).agent_location() {
 4662            let buffer_entity_id = agent_location.buffer.entity_id();
 4663            let view_id = ViewId {
 4664                creator: CollaboratorId::Agent,
 4665                id: buffer_entity_id.as_u64(),
 4666            };
 4667            follower_state.active_view_id = Some(view_id);
 4668
 4669            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 4670                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 4671                hash_map::Entry::Vacant(entry) => {
 4672                    let existing_view =
 4673                        follower_state
 4674                            .center_pane
 4675                            .read(cx)
 4676                            .items()
 4677                            .find_map(|item| {
 4678                                let item = item.to_followable_item_handle(cx)?;
 4679                                if item.is_singleton(cx)
 4680                                    && item.project_item_model_ids(cx).as_slice()
 4681                                        == [buffer_entity_id]
 4682                                {
 4683                                    Some(item)
 4684                                } else {
 4685                                    None
 4686                                }
 4687                            });
 4688                    let view = existing_view.or_else(|| {
 4689                        agent_location.buffer.upgrade().and_then(|buffer| {
 4690                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 4691                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 4692                            })?
 4693                            .to_followable_item_handle(cx)
 4694                        })
 4695                    });
 4696
 4697                    if let Some(view) = view {
 4698                        Some(entry.insert(FollowerView {
 4699                            view,
 4700                            location: None,
 4701                        }))
 4702                    } else {
 4703                        None
 4704                    }
 4705                }
 4706            };
 4707
 4708            if let Some(item) = item {
 4709                item.view
 4710                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 4711                item.view
 4712                    .update_agent_location(agent_location.position, window, cx);
 4713            }
 4714        } else {
 4715            follower_state.active_view_id = None;
 4716        }
 4717
 4718        self.leader_updated(CollaboratorId::Agent, window, cx);
 4719    }
 4720
 4721    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 4722        let mut is_project_item = true;
 4723        let mut update = proto::UpdateActiveView::default();
 4724        if window.is_window_active() {
 4725            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 4726
 4727            if let Some(item) = active_item {
 4728                if item.item_focus_handle(cx).contains_focused(window, cx) {
 4729                    let leader_id = self
 4730                        .pane_for(&*item)
 4731                        .and_then(|pane| self.leader_for_pane(&pane));
 4732                    let leader_peer_id = match leader_id {
 4733                        Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4734                        Some(CollaboratorId::Agent) | None => None,
 4735                    };
 4736
 4737                    if let Some(item) = item.to_followable_item_handle(cx) {
 4738                        let id = item
 4739                            .remote_id(&self.app_state.client, window, cx)
 4740                            .map(|id| id.to_proto());
 4741
 4742                        if let Some(id) = id.clone() {
 4743                            if let Some(variant) = item.to_state_proto(window, cx) {
 4744                                let view = Some(proto::View {
 4745                                    id: id.clone(),
 4746                                    leader_id: leader_peer_id,
 4747                                    variant: Some(variant),
 4748                                    panel_id: panel_id.map(|id| id as i32),
 4749                                });
 4750
 4751                                is_project_item = item.is_project_item(window, cx);
 4752                                update = proto::UpdateActiveView {
 4753                                    view,
 4754                                    // TODO: Remove after version 0.145.x stabilizes.
 4755                                    id: id.clone(),
 4756                                    leader_id: leader_peer_id,
 4757                                };
 4758                            }
 4759                        };
 4760                    }
 4761                }
 4762            }
 4763        }
 4764
 4765        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 4766        if active_view_id != self.last_active_view_id.as_ref() {
 4767            self.last_active_view_id = active_view_id.cloned();
 4768            self.update_followers(
 4769                is_project_item,
 4770                proto::update_followers::Variant::UpdateActiveView(update),
 4771                window,
 4772                cx,
 4773            );
 4774        }
 4775    }
 4776
 4777    fn active_item_for_followers(
 4778        &self,
 4779        window: &mut Window,
 4780        cx: &mut App,
 4781    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 4782        let mut active_item = None;
 4783        let mut panel_id = None;
 4784        for dock in self.all_docks() {
 4785            if dock.focus_handle(cx).contains_focused(window, cx) {
 4786                if let Some(panel) = dock.read(cx).active_panel() {
 4787                    if let Some(pane) = panel.pane(cx) {
 4788                        if let Some(item) = pane.read(cx).active_item() {
 4789                            active_item = Some(item);
 4790                            panel_id = panel.remote_id();
 4791                            break;
 4792                        }
 4793                    }
 4794                }
 4795            }
 4796        }
 4797
 4798        if active_item.is_none() {
 4799            active_item = self.active_pane().read(cx).active_item();
 4800        }
 4801        (active_item, panel_id)
 4802    }
 4803
 4804    fn update_followers(
 4805        &self,
 4806        project_only: bool,
 4807        update: proto::update_followers::Variant,
 4808        _: &mut Window,
 4809        cx: &mut App,
 4810    ) -> Option<()> {
 4811        // If this update only applies to for followers in the current project,
 4812        // then skip it unless this project is shared. If it applies to all
 4813        // followers, regardless of project, then set `project_id` to none,
 4814        // indicating that it goes to all followers.
 4815        let project_id = if project_only {
 4816            Some(self.project.read(cx).remote_id()?)
 4817        } else {
 4818            None
 4819        };
 4820        self.app_state().workspace_store.update(cx, |store, cx| {
 4821            store.update_followers(project_id, update, cx)
 4822        })
 4823    }
 4824
 4825    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 4826        self.follower_states.iter().find_map(|(leader_id, state)| {
 4827            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 4828                Some(*leader_id)
 4829            } else {
 4830                None
 4831            }
 4832        })
 4833    }
 4834
 4835    fn leader_updated(
 4836        &mut self,
 4837        leader_id: impl Into<CollaboratorId>,
 4838        window: &mut Window,
 4839        cx: &mut Context<Self>,
 4840    ) -> Option<Box<dyn ItemHandle>> {
 4841        cx.notify();
 4842
 4843        let leader_id = leader_id.into();
 4844        let (panel_id, item) = match leader_id {
 4845            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 4846            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 4847        };
 4848
 4849        let state = self.follower_states.get(&leader_id)?;
 4850        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 4851        let pane;
 4852        if let Some(panel_id) = panel_id {
 4853            pane = self
 4854                .activate_panel_for_proto_id(panel_id, window, cx)?
 4855                .pane(cx)?;
 4856            let state = self.follower_states.get_mut(&leader_id)?;
 4857            state.dock_pane = Some(pane.clone());
 4858        } else {
 4859            pane = state.center_pane.clone();
 4860            let state = self.follower_states.get_mut(&leader_id)?;
 4861            if let Some(dock_pane) = state.dock_pane.take() {
 4862                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 4863            }
 4864        }
 4865
 4866        pane.update(cx, |pane, cx| {
 4867            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 4868            if let Some(index) = pane.index_for_item(item.as_ref()) {
 4869                pane.activate_item(index, false, false, window, cx);
 4870            } else {
 4871                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 4872            }
 4873
 4874            if focus_active_item {
 4875                pane.focus_active_item(window, cx)
 4876            }
 4877        });
 4878
 4879        Some(item)
 4880    }
 4881
 4882    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 4883        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 4884        let active_view_id = state.active_view_id?;
 4885        Some(
 4886            state
 4887                .items_by_leader_view_id
 4888                .get(&active_view_id)?
 4889                .view
 4890                .boxed_clone(),
 4891        )
 4892    }
 4893
 4894    fn active_item_for_peer(
 4895        &self,
 4896        peer_id: PeerId,
 4897        window: &mut Window,
 4898        cx: &mut Context<Self>,
 4899    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 4900        let call = self.active_call()?;
 4901        let room = call.read(cx).room()?.read(cx);
 4902        let participant = room.remote_participant_for_peer_id(peer_id)?;
 4903        let leader_in_this_app;
 4904        let leader_in_this_project;
 4905        match participant.location {
 4906            call::ParticipantLocation::SharedProject { project_id } => {
 4907                leader_in_this_app = true;
 4908                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 4909            }
 4910            call::ParticipantLocation::UnsharedProject => {
 4911                leader_in_this_app = true;
 4912                leader_in_this_project = false;
 4913            }
 4914            call::ParticipantLocation::External => {
 4915                leader_in_this_app = false;
 4916                leader_in_this_project = false;
 4917            }
 4918        };
 4919        let state = self.follower_states.get(&peer_id.into())?;
 4920        let mut item_to_activate = None;
 4921        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 4922            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id) {
 4923                if leader_in_this_project || !item.view.is_project_item(window, cx) {
 4924                    item_to_activate = Some((item.location, item.view.boxed_clone()));
 4925                }
 4926            }
 4927        } else if let Some(shared_screen) =
 4928            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 4929        {
 4930            item_to_activate = Some((None, Box::new(shared_screen)));
 4931        }
 4932        item_to_activate
 4933    }
 4934
 4935    fn shared_screen_for_peer(
 4936        &self,
 4937        peer_id: PeerId,
 4938        pane: &Entity<Pane>,
 4939        window: &mut Window,
 4940        cx: &mut App,
 4941    ) -> Option<Entity<SharedScreen>> {
 4942        let call = self.active_call()?;
 4943        let room = call.read(cx).room()?.clone();
 4944        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 4945        let track = participant.video_tracks.values().next()?.clone();
 4946        let user = participant.user.clone();
 4947
 4948        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 4949            if item.read(cx).peer_id == peer_id {
 4950                return Some(item);
 4951            }
 4952        }
 4953
 4954        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 4955    }
 4956
 4957    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4958        if window.is_window_active() {
 4959            self.update_active_view_for_followers(window, cx);
 4960
 4961            if let Some(database_id) = self.database_id {
 4962                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 4963                    .detach();
 4964            }
 4965        } else {
 4966            for pane in &self.panes {
 4967                pane.update(cx, |pane, cx| {
 4968                    if let Some(item) = pane.active_item() {
 4969                        item.workspace_deactivated(window, cx);
 4970                    }
 4971                    for item in pane.items() {
 4972                        if matches!(
 4973                            item.workspace_settings(cx).autosave,
 4974                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 4975                        ) {
 4976                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 4977                                .detach_and_log_err(cx);
 4978                        }
 4979                    }
 4980                });
 4981            }
 4982        }
 4983    }
 4984
 4985    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 4986        self.active_call.as_ref().map(|(call, _)| call)
 4987    }
 4988
 4989    fn on_active_call_event(
 4990        &mut self,
 4991        _: &Entity<ActiveCall>,
 4992        event: &call::room::Event,
 4993        window: &mut Window,
 4994        cx: &mut Context<Self>,
 4995    ) {
 4996        match event {
 4997            call::room::Event::ParticipantLocationChanged { participant_id }
 4998            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 4999                self.leader_updated(participant_id, window, cx);
 5000            }
 5001            _ => {}
 5002        }
 5003    }
 5004
 5005    pub fn database_id(&self) -> Option<WorkspaceId> {
 5006        self.database_id
 5007    }
 5008
 5009    pub fn session_id(&self) -> Option<String> {
 5010        self.session_id.clone()
 5011    }
 5012
 5013    fn local_paths(&self, cx: &App) -> Option<Vec<Arc<Path>>> {
 5014        let project = self.project().read(cx);
 5015
 5016        if project.is_local() {
 5017            Some(
 5018                project
 5019                    .visible_worktrees(cx)
 5020                    .map(|worktree| worktree.read(cx).abs_path())
 5021                    .collect::<Vec<_>>(),
 5022            )
 5023        } else {
 5024            None
 5025        }
 5026    }
 5027
 5028    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5029        match member {
 5030            Member::Axis(PaneAxis { members, .. }) => {
 5031                for child in members.iter() {
 5032                    self.remove_panes(child.clone(), window, cx)
 5033                }
 5034            }
 5035            Member::Pane(pane) => {
 5036                self.force_remove_pane(&pane, &None, window, cx);
 5037            }
 5038        }
 5039    }
 5040
 5041    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5042        self.session_id.take();
 5043        self.serialize_workspace_internal(window, cx)
 5044    }
 5045
 5046    fn force_remove_pane(
 5047        &mut self,
 5048        pane: &Entity<Pane>,
 5049        focus_on: &Option<Entity<Pane>>,
 5050        window: &mut Window,
 5051        cx: &mut Context<Workspace>,
 5052    ) {
 5053        self.panes.retain(|p| p != pane);
 5054        if let Some(focus_on) = focus_on {
 5055            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5056        } else {
 5057            if self.active_pane() == pane {
 5058                self.panes
 5059                    .last()
 5060                    .unwrap()
 5061                    .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5062            }
 5063        }
 5064        if self.last_active_center_pane == Some(pane.downgrade()) {
 5065            self.last_active_center_pane = None;
 5066        }
 5067        cx.notify();
 5068    }
 5069
 5070    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5071        if self._schedule_serialize.is_none() {
 5072            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
 5073                cx.background_executor()
 5074                    .timer(Duration::from_millis(100))
 5075                    .await;
 5076                this.update_in(cx, |this, window, cx| {
 5077                    this.serialize_workspace_internal(window, cx).detach();
 5078                    this._schedule_serialize.take();
 5079                })
 5080                .log_err();
 5081            }));
 5082        }
 5083    }
 5084
 5085    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5086        let Some(database_id) = self.database_id() else {
 5087            return Task::ready(());
 5088        };
 5089
 5090        fn serialize_pane_handle(
 5091            pane_handle: &Entity<Pane>,
 5092            window: &mut Window,
 5093            cx: &mut App,
 5094        ) -> SerializedPane {
 5095            let (items, active, pinned_count) = {
 5096                let pane = pane_handle.read(cx);
 5097                let active_item_id = pane.active_item().map(|item| item.item_id());
 5098                (
 5099                    pane.items()
 5100                        .filter_map(|handle| {
 5101                            let handle = handle.to_serializable_item_handle(cx)?;
 5102
 5103                            Some(SerializedItem {
 5104                                kind: Arc::from(handle.serialized_item_kind()),
 5105                                item_id: handle.item_id().as_u64(),
 5106                                active: Some(handle.item_id()) == active_item_id,
 5107                                preview: pane.is_active_preview_item(handle.item_id()),
 5108                            })
 5109                        })
 5110                        .collect::<Vec<_>>(),
 5111                    pane.has_focus(window, cx),
 5112                    pane.pinned_count(),
 5113                )
 5114            };
 5115
 5116            SerializedPane::new(items, active, pinned_count)
 5117        }
 5118
 5119        fn build_serialized_pane_group(
 5120            pane_group: &Member,
 5121            window: &mut Window,
 5122            cx: &mut App,
 5123        ) -> SerializedPaneGroup {
 5124            match pane_group {
 5125                Member::Axis(PaneAxis {
 5126                    axis,
 5127                    members,
 5128                    flexes,
 5129                    bounding_boxes: _,
 5130                }) => SerializedPaneGroup::Group {
 5131                    axis: SerializedAxis(*axis),
 5132                    children: members
 5133                        .iter()
 5134                        .map(|member| build_serialized_pane_group(member, window, cx))
 5135                        .collect::<Vec<_>>(),
 5136                    flexes: Some(flexes.lock().clone()),
 5137                },
 5138                Member::Pane(pane_handle) => {
 5139                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5140                }
 5141            }
 5142        }
 5143
 5144        fn build_serialized_docks(
 5145            this: &Workspace,
 5146            window: &mut Window,
 5147            cx: &mut App,
 5148        ) -> DockStructure {
 5149            let left_dock = this.left_dock.read(cx);
 5150            let left_visible = left_dock.is_open();
 5151            let left_active_panel = left_dock
 5152                .active_panel()
 5153                .map(|panel| panel.persistent_name().to_string());
 5154            let left_dock_zoom = left_dock
 5155                .active_panel()
 5156                .map(|panel| panel.is_zoomed(window, cx))
 5157                .unwrap_or(false);
 5158
 5159            let right_dock = this.right_dock.read(cx);
 5160            let right_visible = right_dock.is_open();
 5161            let right_active_panel = right_dock
 5162                .active_panel()
 5163                .map(|panel| panel.persistent_name().to_string());
 5164            let right_dock_zoom = right_dock
 5165                .active_panel()
 5166                .map(|panel| panel.is_zoomed(window, cx))
 5167                .unwrap_or(false);
 5168
 5169            let bottom_dock = this.bottom_dock.read(cx);
 5170            let bottom_visible = bottom_dock.is_open();
 5171            let bottom_active_panel = bottom_dock
 5172                .active_panel()
 5173                .map(|panel| panel.persistent_name().to_string());
 5174            let bottom_dock_zoom = bottom_dock
 5175                .active_panel()
 5176                .map(|panel| panel.is_zoomed(window, cx))
 5177                .unwrap_or(false);
 5178
 5179            DockStructure {
 5180                left: DockData {
 5181                    visible: left_visible,
 5182                    active_panel: left_active_panel,
 5183                    zoom: left_dock_zoom,
 5184                },
 5185                right: DockData {
 5186                    visible: right_visible,
 5187                    active_panel: right_active_panel,
 5188                    zoom: right_dock_zoom,
 5189                },
 5190                bottom: DockData {
 5191                    visible: bottom_visible,
 5192                    active_panel: bottom_active_panel,
 5193                    zoom: bottom_dock_zoom,
 5194                },
 5195            }
 5196        }
 5197
 5198        if let Some(location) = self.serialize_workspace_location(cx) {
 5199            let breakpoints = self.project.update(cx, |project, cx| {
 5200                project
 5201                    .breakpoint_store()
 5202                    .read(cx)
 5203                    .all_source_breakpoints(cx)
 5204            });
 5205
 5206            let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5207            let docks = build_serialized_docks(self, window, cx);
 5208            let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5209            let serialized_workspace = SerializedWorkspace {
 5210                id: database_id,
 5211                location,
 5212                center_group,
 5213                window_bounds,
 5214                display: Default::default(),
 5215                docks,
 5216                centered_layout: self.centered_layout,
 5217                session_id: self.session_id.clone(),
 5218                breakpoints,
 5219                window_id: Some(window.window_handle().window_id().as_u64()),
 5220            };
 5221
 5222            return window.spawn(cx, async move |_| {
 5223                persistence::DB.save_workspace(serialized_workspace).await;
 5224            });
 5225        }
 5226        Task::ready(())
 5227    }
 5228
 5229    fn serialize_workspace_location(&self, cx: &App) -> Option<SerializedWorkspaceLocation> {
 5230        if let Some(ssh_project) = &self.serialized_ssh_project {
 5231            Some(SerializedWorkspaceLocation::Ssh(ssh_project.clone()))
 5232        } else if let Some(local_paths) = self.local_paths(cx) {
 5233            if !local_paths.is_empty() {
 5234                Some(SerializedWorkspaceLocation::from_local_paths(local_paths))
 5235            } else {
 5236                None
 5237            }
 5238        } else {
 5239            None
 5240        }
 5241    }
 5242
 5243    fn update_history(&self, cx: &mut App) {
 5244        let Some(id) = self.database_id() else {
 5245            return;
 5246        };
 5247        let Some(location) = self.serialize_workspace_location(cx) else {
 5248            return;
 5249        };
 5250        if let Some(manager) = HistoryManager::global(cx) {
 5251            manager.update(cx, |this, cx| {
 5252                this.update_history(id, HistoryManagerEntry::new(id, &location), cx);
 5253            });
 5254        }
 5255    }
 5256
 5257    async fn serialize_items(
 5258        this: &WeakEntity<Self>,
 5259        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5260        cx: &mut AsyncWindowContext,
 5261    ) -> Result<()> {
 5262        const CHUNK_SIZE: usize = 200;
 5263
 5264        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5265
 5266        while let Some(items_received) = serializable_items.next().await {
 5267            let unique_items =
 5268                items_received
 5269                    .into_iter()
 5270                    .fold(HashMap::default(), |mut acc, item| {
 5271                        acc.entry(item.item_id()).or_insert(item);
 5272                        acc
 5273                    });
 5274
 5275            // We use into_iter() here so that the references to the items are moved into
 5276            // the tasks and not kept alive while we're sleeping.
 5277            for (_, item) in unique_items.into_iter() {
 5278                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5279                    item.serialize(workspace, false, window, cx)
 5280                }) {
 5281                    cx.background_spawn(async move { task.await.log_err() })
 5282                        .detach();
 5283                }
 5284            }
 5285
 5286            cx.background_executor()
 5287                .timer(SERIALIZATION_THROTTLE_TIME)
 5288                .await;
 5289        }
 5290
 5291        Ok(())
 5292    }
 5293
 5294    pub(crate) fn enqueue_item_serialization(
 5295        &mut self,
 5296        item: Box<dyn SerializableItemHandle>,
 5297    ) -> Result<()> {
 5298        self.serializable_items_tx
 5299            .unbounded_send(item)
 5300            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5301    }
 5302
 5303    pub(crate) fn load_workspace(
 5304        serialized_workspace: SerializedWorkspace,
 5305        paths_to_open: Vec<Option<ProjectPath>>,
 5306        window: &mut Window,
 5307        cx: &mut Context<Workspace>,
 5308    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5309        cx.spawn_in(window, async move |workspace, cx| {
 5310            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5311
 5312            let mut center_group = None;
 5313            let mut center_items = None;
 5314
 5315            // Traverse the splits tree and add to things
 5316            if let Some((group, active_pane, items)) = serialized_workspace
 5317                .center_group
 5318                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5319                .await
 5320            {
 5321                center_items = Some(items);
 5322                center_group = Some((group, active_pane))
 5323            }
 5324
 5325            let mut items_by_project_path = HashMap::default();
 5326            let mut item_ids_by_kind = HashMap::default();
 5327            let mut all_deserialized_items = Vec::default();
 5328            cx.update(|_, cx| {
 5329                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5330                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5331                        item_ids_by_kind
 5332                            .entry(serializable_item_handle.serialized_item_kind())
 5333                            .or_insert(Vec::new())
 5334                            .push(item.item_id().as_u64() as ItemId);
 5335                    }
 5336
 5337                    if let Some(project_path) = item.project_path(cx) {
 5338                        items_by_project_path.insert(project_path, item.clone());
 5339                    }
 5340                    all_deserialized_items.push(item);
 5341                }
 5342            })?;
 5343
 5344            let opened_items = paths_to_open
 5345                .into_iter()
 5346                .map(|path_to_open| {
 5347                    path_to_open
 5348                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5349                })
 5350                .collect::<Vec<_>>();
 5351
 5352            // Remove old panes from workspace panes list
 5353            workspace.update_in(cx, |workspace, window, cx| {
 5354                if let Some((center_group, active_pane)) = center_group {
 5355                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5356
 5357                    // Swap workspace center group
 5358                    workspace.center = PaneGroup::with_root(center_group);
 5359                    if let Some(active_pane) = active_pane {
 5360                        workspace.set_active_pane(&active_pane, window, cx);
 5361                        cx.focus_self(window);
 5362                    } else {
 5363                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5364                    }
 5365                }
 5366
 5367                let docks = serialized_workspace.docks;
 5368
 5369                for (dock, serialized_dock) in [
 5370                    (&mut workspace.right_dock, docks.right),
 5371                    (&mut workspace.left_dock, docks.left),
 5372                    (&mut workspace.bottom_dock, docks.bottom),
 5373                ]
 5374                .iter_mut()
 5375                {
 5376                    dock.update(cx, |dock, cx| {
 5377                        dock.serialized_dock = Some(serialized_dock.clone());
 5378                        dock.restore_state(window, cx);
 5379                    });
 5380                }
 5381
 5382                cx.notify();
 5383            })?;
 5384
 5385            let _ = project
 5386                .update(cx, |project, cx| {
 5387                    project
 5388                        .breakpoint_store()
 5389                        .update(cx, |breakpoint_store, cx| {
 5390                            breakpoint_store
 5391                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5392                        })
 5393                })?
 5394                .await;
 5395
 5396            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5397            // after loading the items, we might have different items and in order to avoid
 5398            // the database filling up, we delete items that haven't been loaded now.
 5399            //
 5400            // The items that have been loaded, have been saved after they've been added to the workspace.
 5401            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5402                item_ids_by_kind
 5403                    .into_iter()
 5404                    .map(|(item_kind, loaded_items)| {
 5405                        SerializableItemRegistry::cleanup(
 5406                            item_kind,
 5407                            serialized_workspace.id,
 5408                            loaded_items,
 5409                            window,
 5410                            cx,
 5411                        )
 5412                        .log_err()
 5413                    })
 5414                    .collect::<Vec<_>>()
 5415            })?;
 5416
 5417            futures::future::join_all(clean_up_tasks).await;
 5418
 5419            workspace
 5420                .update_in(cx, |workspace, window, cx| {
 5421                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5422                    workspace.serialize_workspace_internal(window, cx).detach();
 5423
 5424                    // Ensure that we mark the window as edited if we did load dirty items
 5425                    workspace.update_window_edited(window, cx);
 5426                })
 5427                .ok();
 5428
 5429            Ok(opened_items)
 5430        })
 5431    }
 5432
 5433    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5434        self.add_workspace_actions_listeners(div, window, cx)
 5435            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5436            .on_action(cx.listener(Self::close_all_items_and_panes))
 5437            .on_action(cx.listener(Self::save_all))
 5438            .on_action(cx.listener(Self::send_keystrokes))
 5439            .on_action(cx.listener(Self::add_folder_to_project))
 5440            .on_action(cx.listener(Self::follow_next_collaborator))
 5441            .on_action(cx.listener(Self::close_window))
 5442            .on_action(cx.listener(Self::activate_pane_at_index))
 5443            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5444            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5445            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5446                let pane = workspace.active_pane().clone();
 5447                workspace.unfollow_in_pane(&pane, window, cx);
 5448            }))
 5449            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5450                workspace
 5451                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5452                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5453            }))
 5454            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5455                workspace
 5456                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5457                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5458            }))
 5459            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5460                workspace
 5461                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5462                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5463            }))
 5464            .on_action(
 5465                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5466                    workspace.activate_previous_pane(window, cx)
 5467                }),
 5468            )
 5469            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5470                workspace.activate_next_pane(window, cx)
 5471            }))
 5472            .on_action(
 5473                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5474                    workspace.activate_next_window(cx)
 5475                }),
 5476            )
 5477            .on_action(
 5478                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5479                    workspace.activate_previous_window(cx)
 5480                }),
 5481            )
 5482            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5483                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5484            }))
 5485            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5486                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5487            }))
 5488            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5489                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5490            }))
 5491            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 5492                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 5493            }))
 5494            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5495                workspace.activate_next_pane(window, cx)
 5496            }))
 5497            .on_action(cx.listener(
 5498                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 5499                    workspace.move_item_to_pane_in_direction(action, window, cx)
 5500                },
 5501            ))
 5502            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 5503                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 5504            }))
 5505            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 5506                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 5507            }))
 5508            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 5509                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 5510            }))
 5511            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 5512                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 5513            }))
 5514            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 5515                this.toggle_dock(DockPosition::Left, window, cx);
 5516            }))
 5517            .on_action(cx.listener(
 5518                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 5519                    workspace.toggle_dock(DockPosition::Right, window, cx);
 5520                },
 5521            ))
 5522            .on_action(cx.listener(
 5523                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 5524                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 5525                },
 5526            ))
 5527            .on_action(cx.listener(
 5528                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 5529                    if !workspace.close_active_dock(window, cx) {
 5530                        cx.propagate();
 5531                    }
 5532                },
 5533            ))
 5534            .on_action(
 5535                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 5536                    workspace.close_all_docks(window, cx);
 5537                }),
 5538            )
 5539            .on_action(cx.listener(
 5540                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 5541                    workspace.clear_all_notifications(cx);
 5542                },
 5543            ))
 5544            .on_action(cx.listener(
 5545                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 5546                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 5547                        workspace.suppress_notification(&notification_id, cx);
 5548                    }
 5549                },
 5550            ))
 5551            .on_action(cx.listener(
 5552                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 5553                    workspace.reopen_closed_item(window, cx).detach();
 5554                },
 5555            ))
 5556            .on_action(cx.listener(
 5557                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 5558                    for dock in workspace.all_docks() {
 5559                        if dock.focus_handle(cx).contains_focused(window, cx) {
 5560                            let Some(panel) = dock.read(cx).active_panel() else {
 5561                                return;
 5562                            };
 5563
 5564                            // Set to `None`, then the size will fall back to the default.
 5565                            panel.clone().set_size(None, window, cx);
 5566
 5567                            return;
 5568                        }
 5569                    }
 5570                },
 5571            ))
 5572            .on_action(cx.listener(
 5573                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 5574                    for dock in workspace.all_docks() {
 5575                        if let Some(panel) = dock.read(cx).visible_panel() {
 5576                            // Set to `None`, then the size will fall back to the default.
 5577                            panel.clone().set_size(None, window, cx);
 5578                        }
 5579                    }
 5580                },
 5581            ))
 5582            .on_action(cx.listener(
 5583                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 5584                    adjust_active_dock_size_by_px(
 5585                        px_with_ui_font_fallback(act.px, cx),
 5586                        workspace,
 5587                        window,
 5588                        cx,
 5589                    );
 5590                },
 5591            ))
 5592            .on_action(cx.listener(
 5593                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 5594                    adjust_active_dock_size_by_px(
 5595                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5596                        workspace,
 5597                        window,
 5598                        cx,
 5599                    );
 5600                },
 5601            ))
 5602            .on_action(cx.listener(
 5603                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 5604                    adjust_open_docks_size_by_px(
 5605                        px_with_ui_font_fallback(act.px, cx),
 5606                        workspace,
 5607                        window,
 5608                        cx,
 5609                    );
 5610                },
 5611            ))
 5612            .on_action(cx.listener(
 5613                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 5614                    adjust_open_docks_size_by_px(
 5615                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5616                        workspace,
 5617                        window,
 5618                        cx,
 5619                    );
 5620                },
 5621            ))
 5622            .on_action(cx.listener(Workspace::toggle_centered_layout))
 5623            .on_action(cx.listener(Workspace::cancel))
 5624    }
 5625
 5626    #[cfg(any(test, feature = "test-support"))]
 5627    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 5628        use node_runtime::NodeRuntime;
 5629        use session::Session;
 5630
 5631        let client = project.read(cx).client();
 5632        let user_store = project.read(cx).user_store();
 5633
 5634        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 5635        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 5636        window.activate_window();
 5637        let app_state = Arc::new(AppState {
 5638            languages: project.read(cx).languages().clone(),
 5639            workspace_store,
 5640            client,
 5641            user_store,
 5642            fs: project.read(cx).fs().clone(),
 5643            build_window_options: |_, _| Default::default(),
 5644            node_runtime: NodeRuntime::unavailable(),
 5645            session,
 5646        });
 5647        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 5648        workspace
 5649            .active_pane
 5650            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5651        workspace
 5652    }
 5653
 5654    pub fn register_action<A: Action>(
 5655        &mut self,
 5656        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 5657    ) -> &mut Self {
 5658        let callback = Arc::new(callback);
 5659
 5660        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 5661            let callback = callback.clone();
 5662            div.on_action(cx.listener(move |workspace, event, window, cx| {
 5663                (callback)(workspace, event, window, cx)
 5664            }))
 5665        }));
 5666        self
 5667    }
 5668    pub fn register_action_renderer(
 5669        &mut self,
 5670        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 5671    ) -> &mut Self {
 5672        self.workspace_actions.push(Box::new(callback));
 5673        self
 5674    }
 5675
 5676    fn add_workspace_actions_listeners(
 5677        &self,
 5678        mut div: Div,
 5679        window: &mut Window,
 5680        cx: &mut Context<Self>,
 5681    ) -> Div {
 5682        for action in self.workspace_actions.iter() {
 5683            div = (action)(div, self, window, cx)
 5684        }
 5685        div
 5686    }
 5687
 5688    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 5689        self.modal_layer.read(cx).has_active_modal()
 5690    }
 5691
 5692    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 5693        self.modal_layer.read(cx).active_modal()
 5694    }
 5695
 5696    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 5697    where
 5698        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 5699    {
 5700        self.modal_layer.update(cx, |modal_layer, cx| {
 5701            modal_layer.toggle_modal(window, cx, build)
 5702        })
 5703    }
 5704
 5705    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 5706        self.toast_layer
 5707            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 5708    }
 5709
 5710    pub fn toggle_centered_layout(
 5711        &mut self,
 5712        _: &ToggleCenteredLayout,
 5713        _: &mut Window,
 5714        cx: &mut Context<Self>,
 5715    ) {
 5716        self.centered_layout = !self.centered_layout;
 5717        if let Some(database_id) = self.database_id() {
 5718            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 5719                .detach_and_log_err(cx);
 5720        }
 5721        cx.notify();
 5722    }
 5723
 5724    fn adjust_padding(padding: Option<f32>) -> f32 {
 5725        padding
 5726            .unwrap_or(Self::DEFAULT_PADDING)
 5727            .clamp(0.0, Self::MAX_PADDING)
 5728    }
 5729
 5730    fn render_dock(
 5731        &self,
 5732        position: DockPosition,
 5733        dock: &Entity<Dock>,
 5734        window: &mut Window,
 5735        cx: &mut App,
 5736    ) -> Option<Div> {
 5737        if self.zoomed_position == Some(position) {
 5738            return None;
 5739        }
 5740
 5741        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 5742            let pane = panel.pane(cx)?;
 5743            let follower_states = &self.follower_states;
 5744            leader_border_for_pane(follower_states, &pane, window, cx)
 5745        });
 5746
 5747        Some(
 5748            div()
 5749                .flex()
 5750                .flex_none()
 5751                .overflow_hidden()
 5752                .child(dock.clone())
 5753                .children(leader_border),
 5754        )
 5755    }
 5756
 5757    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 5758        window.root().flatten()
 5759    }
 5760
 5761    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 5762        self.zoomed.as_ref()
 5763    }
 5764
 5765    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 5766        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 5767            return;
 5768        };
 5769        let windows = cx.windows();
 5770        let Some(next_window) = windows
 5771            .iter()
 5772            .cycle()
 5773            .skip_while(|window| window.window_id() != current_window_id)
 5774            .nth(1)
 5775        else {
 5776            return;
 5777        };
 5778        next_window
 5779            .update(cx, |_, window, _| window.activate_window())
 5780            .ok();
 5781    }
 5782
 5783    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 5784        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 5785            return;
 5786        };
 5787        let windows = cx.windows();
 5788        let Some(prev_window) = windows
 5789            .iter()
 5790            .rev()
 5791            .cycle()
 5792            .skip_while(|window| window.window_id() != current_window_id)
 5793            .nth(1)
 5794        else {
 5795            return;
 5796        };
 5797        prev_window
 5798            .update(cx, |_, window, _| window.activate_window())
 5799            .ok();
 5800    }
 5801
 5802    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 5803        if cx.stop_active_drag(window) {
 5804            return;
 5805        } else if let Some((notification_id, _)) = self.notifications.pop() {
 5806            dismiss_app_notification(&notification_id, cx);
 5807        } else {
 5808            cx.propagate();
 5809        }
 5810    }
 5811
 5812    fn adjust_dock_size_by_px(
 5813        &mut self,
 5814        panel_size: Pixels,
 5815        dock_pos: DockPosition,
 5816        px: Pixels,
 5817        window: &mut Window,
 5818        cx: &mut Context<Self>,
 5819    ) {
 5820        match dock_pos {
 5821            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 5822            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 5823            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 5824        }
 5825    }
 5826
 5827    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5828        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 5829
 5830        self.left_dock.update(cx, |left_dock, cx| {
 5831            if WorkspaceSettings::get_global(cx)
 5832                .resize_all_panels_in_dock
 5833                .contains(&DockPosition::Left)
 5834            {
 5835                left_dock.resize_all_panels(Some(size), window, cx);
 5836            } else {
 5837                left_dock.resize_active_panel(Some(size), window, cx);
 5838            }
 5839        });
 5840    }
 5841
 5842    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5843        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 5844        self.left_dock.read_with(cx, |left_dock, cx| {
 5845            let left_dock_size = left_dock
 5846                .active_panel_size(window, cx)
 5847                .unwrap_or(Pixels(0.0));
 5848            if left_dock_size + size > self.bounds.right() {
 5849                size = self.bounds.right() - left_dock_size
 5850            }
 5851        });
 5852        self.right_dock.update(cx, |right_dock, cx| {
 5853            if WorkspaceSettings::get_global(cx)
 5854                .resize_all_panels_in_dock
 5855                .contains(&DockPosition::Right)
 5856            {
 5857                right_dock.resize_all_panels(Some(size), window, cx);
 5858            } else {
 5859                right_dock.resize_active_panel(Some(size), window, cx);
 5860            }
 5861        });
 5862    }
 5863
 5864    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5865        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 5866        self.bottom_dock.update(cx, |bottom_dock, cx| {
 5867            if WorkspaceSettings::get_global(cx)
 5868                .resize_all_panels_in_dock
 5869                .contains(&DockPosition::Bottom)
 5870            {
 5871                bottom_dock.resize_all_panels(Some(size), window, cx);
 5872            } else {
 5873                bottom_dock.resize_active_panel(Some(size), window, cx);
 5874            }
 5875        });
 5876    }
 5877}
 5878
 5879fn leader_border_for_pane(
 5880    follower_states: &HashMap<CollaboratorId, FollowerState>,
 5881    pane: &Entity<Pane>,
 5882    _: &Window,
 5883    cx: &App,
 5884) -> Option<Div> {
 5885    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 5886        if state.pane() == pane {
 5887            Some((*leader_id, state))
 5888        } else {
 5889            None
 5890        }
 5891    })?;
 5892
 5893    let mut leader_color = match leader_id {
 5894        CollaboratorId::PeerId(leader_peer_id) => {
 5895            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 5896            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 5897
 5898            cx.theme()
 5899                .players()
 5900                .color_for_participant(leader.participant_index.0)
 5901                .cursor
 5902        }
 5903        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 5904    };
 5905    leader_color.fade_out(0.3);
 5906    Some(
 5907        div()
 5908            .absolute()
 5909            .size_full()
 5910            .left_0()
 5911            .top_0()
 5912            .border_2()
 5913            .border_color(leader_color),
 5914    )
 5915}
 5916
 5917fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 5918    ZED_WINDOW_POSITION
 5919        .zip(*ZED_WINDOW_SIZE)
 5920        .map(|(position, size)| Bounds {
 5921            origin: position,
 5922            size,
 5923        })
 5924}
 5925
 5926fn open_items(
 5927    serialized_workspace: Option<SerializedWorkspace>,
 5928    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 5929    window: &mut Window,
 5930    cx: &mut Context<Workspace>,
 5931) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 5932    let restored_items = serialized_workspace.map(|serialized_workspace| {
 5933        Workspace::load_workspace(
 5934            serialized_workspace,
 5935            project_paths_to_open
 5936                .iter()
 5937                .map(|(_, project_path)| project_path)
 5938                .cloned()
 5939                .collect(),
 5940            window,
 5941            cx,
 5942        )
 5943    });
 5944
 5945    cx.spawn_in(window, async move |workspace, cx| {
 5946        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 5947
 5948        if let Some(restored_items) = restored_items {
 5949            let restored_items = restored_items.await?;
 5950
 5951            let restored_project_paths = restored_items
 5952                .iter()
 5953                .filter_map(|item| {
 5954                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 5955                        .ok()
 5956                        .flatten()
 5957                })
 5958                .collect::<HashSet<_>>();
 5959
 5960            for restored_item in restored_items {
 5961                opened_items.push(restored_item.map(Ok));
 5962            }
 5963
 5964            project_paths_to_open
 5965                .iter_mut()
 5966                .for_each(|(_, project_path)| {
 5967                    if let Some(project_path_to_open) = project_path {
 5968                        if restored_project_paths.contains(project_path_to_open) {
 5969                            *project_path = None;
 5970                        }
 5971                    }
 5972                });
 5973        } else {
 5974            for _ in 0..project_paths_to_open.len() {
 5975                opened_items.push(None);
 5976            }
 5977        }
 5978        assert!(opened_items.len() == project_paths_to_open.len());
 5979
 5980        let tasks =
 5981            project_paths_to_open
 5982                .into_iter()
 5983                .enumerate()
 5984                .map(|(ix, (abs_path, project_path))| {
 5985                    let workspace = workspace.clone();
 5986                    cx.spawn(async move |cx| {
 5987                        let file_project_path = project_path?;
 5988                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 5989                            workspace.project().update(cx, |project, cx| {
 5990                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 5991                            })
 5992                        });
 5993
 5994                        // We only want to open file paths here. If one of the items
 5995                        // here is a directory, it was already opened further above
 5996                        // with a `find_or_create_worktree`.
 5997                        if let Ok(task) = abs_path_task {
 5998                            if task.await.map_or(true, |p| p.is_file()) {
 5999                                return Some((
 6000                                    ix,
 6001                                    workspace
 6002                                        .update_in(cx, |workspace, window, cx| {
 6003                                            workspace.open_path(
 6004                                                file_project_path,
 6005                                                None,
 6006                                                true,
 6007                                                window,
 6008                                                cx,
 6009                                            )
 6010                                        })
 6011                                        .log_err()?
 6012                                        .await,
 6013                                ));
 6014                            }
 6015                        }
 6016                        None
 6017                    })
 6018                });
 6019
 6020        let tasks = tasks.collect::<Vec<_>>();
 6021
 6022        let tasks = futures::future::join_all(tasks);
 6023        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6024            opened_items[ix] = Some(path_open_result);
 6025        }
 6026
 6027        Ok(opened_items)
 6028    })
 6029}
 6030
 6031enum ActivateInDirectionTarget {
 6032    Pane(Entity<Pane>),
 6033    Dock(Entity<Dock>),
 6034}
 6035
 6036fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6037    workspace
 6038        .update(cx, |workspace, _, cx| {
 6039            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6040                struct DatabaseFailedNotification;
 6041
 6042                workspace.show_notification(
 6043                    NotificationId::unique::<DatabaseFailedNotification>(),
 6044                    cx,
 6045                    |cx| {
 6046                        cx.new(|cx| {
 6047                            MessageNotification::new("Failed to load the database file.", cx)
 6048                                .primary_message("File an Issue")
 6049                                .primary_icon(IconName::Plus)
 6050                                .primary_on_click(|window, cx| {
 6051                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6052                                })
 6053                        })
 6054                    },
 6055                );
 6056            }
 6057        })
 6058        .log_err();
 6059}
 6060
 6061fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6062    if val == 0 {
 6063        ThemeSettings::get_global(cx).ui_font_size(cx)
 6064    } else {
 6065        px(val as f32)
 6066    }
 6067}
 6068
 6069fn adjust_active_dock_size_by_px(
 6070    px: Pixels,
 6071    workspace: &mut Workspace,
 6072    window: &mut Window,
 6073    cx: &mut Context<Workspace>,
 6074) {
 6075    let Some(active_dock) = workspace
 6076        .all_docks()
 6077        .into_iter()
 6078        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6079    else {
 6080        return;
 6081    };
 6082    let dock = active_dock.read(cx);
 6083    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6084        return;
 6085    };
 6086    let dock_pos = dock.position();
 6087    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6088}
 6089
 6090fn adjust_open_docks_size_by_px(
 6091    px: Pixels,
 6092    workspace: &mut Workspace,
 6093    window: &mut Window,
 6094    cx: &mut Context<Workspace>,
 6095) {
 6096    let docks = workspace
 6097        .all_docks()
 6098        .into_iter()
 6099        .filter_map(|dock| {
 6100            if dock.read(cx).is_open() {
 6101                let dock = dock.read(cx);
 6102                let panel_size = dock.active_panel_size(window, cx)?;
 6103                let dock_pos = dock.position();
 6104                Some((panel_size, dock_pos, px))
 6105            } else {
 6106                None
 6107            }
 6108        })
 6109        .collect::<Vec<_>>();
 6110
 6111    docks
 6112        .into_iter()
 6113        .for_each(|(panel_size, dock_pos, offset)| {
 6114            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6115        });
 6116}
 6117
 6118impl Focusable for Workspace {
 6119    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6120        self.active_pane.focus_handle(cx)
 6121    }
 6122}
 6123
 6124#[derive(Clone)]
 6125struct DraggedDock(DockPosition);
 6126
 6127impl Render for DraggedDock {
 6128    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6129        gpui::Empty
 6130    }
 6131}
 6132
 6133impl Render for Workspace {
 6134    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6135        let mut context = KeyContext::new_with_defaults();
 6136        context.add("Workspace");
 6137        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6138        if let Some(status) = self
 6139            .debugger_provider
 6140            .as_ref()
 6141            .and_then(|provider| provider.active_thread_state(cx))
 6142        {
 6143            match status {
 6144                ThreadStatus::Running | ThreadStatus::Stepping => {
 6145                    context.add("debugger_running");
 6146                }
 6147                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6148                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6149            }
 6150        }
 6151
 6152        let centered_layout = self.centered_layout
 6153            && self.center.panes().len() == 1
 6154            && self.active_item(cx).is_some();
 6155        let render_padding = |size| {
 6156            (size > 0.0).then(|| {
 6157                div()
 6158                    .h_full()
 6159                    .w(relative(size))
 6160                    .bg(cx.theme().colors().editor_background)
 6161                    .border_color(cx.theme().colors().pane_group_border)
 6162            })
 6163        };
 6164        let paddings = if centered_layout {
 6165            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6166            (
 6167                render_padding(Self::adjust_padding(settings.left_padding)),
 6168                render_padding(Self::adjust_padding(settings.right_padding)),
 6169            )
 6170        } else {
 6171            (None, None)
 6172        };
 6173        let ui_font = theme::setup_ui_font(window, cx);
 6174
 6175        let theme = cx.theme().clone();
 6176        let colors = theme.colors();
 6177        let notification_entities = self
 6178            .notifications
 6179            .iter()
 6180            .map(|(_, notification)| notification.entity_id())
 6181            .collect::<Vec<_>>();
 6182
 6183        client_side_decorations(
 6184            self.actions(div(), window, cx)
 6185                .key_context(context)
 6186                .relative()
 6187                .size_full()
 6188                .flex()
 6189                .flex_col()
 6190                .font(ui_font)
 6191                .gap_0()
 6192                .justify_start()
 6193                .items_start()
 6194                .text_color(colors.text)
 6195                .overflow_hidden()
 6196                .children(self.titlebar_item.clone())
 6197                .on_modifiers_changed(move |_, _, cx| {
 6198                    for &id in &notification_entities {
 6199                        cx.notify(id);
 6200                    }
 6201                })
 6202                .child(
 6203                    div()
 6204                        .size_full()
 6205                        .relative()
 6206                        .flex_1()
 6207                        .flex()
 6208                        .flex_col()
 6209                        .child(
 6210                            div()
 6211                                .id("workspace")
 6212                                .bg(colors.background)
 6213                                .relative()
 6214                                .flex_1()
 6215                                .w_full()
 6216                                .flex()
 6217                                .flex_col()
 6218                                .overflow_hidden()
 6219                                .border_t_1()
 6220                                .border_b_1()
 6221                                .border_color(colors.border)
 6222                                .child({
 6223                                    let this = cx.entity().clone();
 6224                                    canvas(
 6225                                        move |bounds, window, cx| {
 6226                                            this.update(cx, |this, cx| {
 6227                                                let bounds_changed = this.bounds != bounds;
 6228                                                this.bounds = bounds;
 6229
 6230                                                if bounds_changed {
 6231                                                    this.left_dock.update(cx, |dock, cx| {
 6232                                                        dock.clamp_panel_size(
 6233                                                            bounds.size.width,
 6234                                                            window,
 6235                                                            cx,
 6236                                                        )
 6237                                                    });
 6238
 6239                                                    this.right_dock.update(cx, |dock, cx| {
 6240                                                        dock.clamp_panel_size(
 6241                                                            bounds.size.width,
 6242                                                            window,
 6243                                                            cx,
 6244                                                        )
 6245                                                    });
 6246
 6247                                                    this.bottom_dock.update(cx, |dock, cx| {
 6248                                                        dock.clamp_panel_size(
 6249                                                            bounds.size.height,
 6250                                                            window,
 6251                                                            cx,
 6252                                                        )
 6253                                                    });
 6254                                                }
 6255                                            })
 6256                                        },
 6257                                        |_, _, _, _| {},
 6258                                    )
 6259                                    .absolute()
 6260                                    .size_full()
 6261                                })
 6262                                .when(self.zoomed.is_none(), |this| {
 6263                                    this.on_drag_move(cx.listener(
 6264                                        move |workspace,
 6265                                              e: &DragMoveEvent<DraggedDock>,
 6266                                              window,
 6267                                              cx| {
 6268                                            if workspace.previous_dock_drag_coordinates
 6269                                                != Some(e.event.position)
 6270                                            {
 6271                                                workspace.previous_dock_drag_coordinates =
 6272                                                    Some(e.event.position);
 6273                                                match e.drag(cx).0 {
 6274                                                    DockPosition::Left => {
 6275                                                        workspace.resize_left_dock(
 6276                                                            e.event.position.x
 6277                                                                - workspace.bounds.left(),
 6278                                                            window,
 6279                                                            cx,
 6280                                                        );
 6281                                                    }
 6282                                                    DockPosition::Right => {
 6283                                                        workspace.resize_right_dock(
 6284                                                            workspace.bounds.right()
 6285                                                                - e.event.position.x,
 6286                                                            window,
 6287                                                            cx,
 6288                                                        );
 6289                                                    }
 6290                                                    DockPosition::Bottom => {
 6291                                                        workspace.resize_bottom_dock(
 6292                                                            workspace.bounds.bottom()
 6293                                                                - e.event.position.y,
 6294                                                            window,
 6295                                                            cx,
 6296                                                        );
 6297                                                    }
 6298                                                };
 6299                                                workspace.serialize_workspace(window, cx);
 6300                                            }
 6301                                        },
 6302                                    ))
 6303                                })
 6304                                .child({
 6305                                    match self.bottom_dock_layout {
 6306                                        BottomDockLayout::Full => div()
 6307                                            .flex()
 6308                                            .flex_col()
 6309                                            .h_full()
 6310                                            .child(
 6311                                                div()
 6312                                                    .flex()
 6313                                                    .flex_row()
 6314                                                    .flex_1()
 6315                                                    .overflow_hidden()
 6316                                                    .children(self.render_dock(
 6317                                                        DockPosition::Left,
 6318                                                        &self.left_dock,
 6319                                                        window,
 6320                                                        cx,
 6321                                                    ))
 6322                                                    .child(
 6323                                                        div()
 6324                                                            .flex()
 6325                                                            .flex_col()
 6326                                                            .flex_1()
 6327                                                            .overflow_hidden()
 6328                                                            .child(
 6329                                                                h_flex()
 6330                                                                    .flex_1()
 6331                                                                    .when_some(
 6332                                                                        paddings.0,
 6333                                                                        |this, p| {
 6334                                                                            this.child(
 6335                                                                                p.border_r_1(),
 6336                                                                            )
 6337                                                                        },
 6338                                                                    )
 6339                                                                    .child(self.center.render(
 6340                                                                        self.zoomed.as_ref(),
 6341                                                                        &PaneRenderContext {
 6342                                                                            follower_states:
 6343                                                                                &self.follower_states,
 6344                                                                            active_call: self.active_call(),
 6345                                                                            active_pane: &self.active_pane,
 6346                                                                            app_state: &self.app_state,
 6347                                                                            project: &self.project,
 6348                                                                            workspace: &self.weak_self,
 6349                                                                        },
 6350                                                                        window,
 6351                                                                        cx,
 6352                                                                    ))
 6353                                                                    .when_some(
 6354                                                                        paddings.1,
 6355                                                                        |this, p| {
 6356                                                                            this.child(
 6357                                                                                p.border_l_1(),
 6358                                                                            )
 6359                                                                        },
 6360                                                                    ),
 6361                                                            ),
 6362                                                    )
 6363                                                    .children(self.render_dock(
 6364                                                        DockPosition::Right,
 6365                                                        &self.right_dock,
 6366                                                        window,
 6367                                                        cx,
 6368                                                    )),
 6369                                            )
 6370                                            .child(div().w_full().children(self.render_dock(
 6371                                                DockPosition::Bottom,
 6372                                                &self.bottom_dock,
 6373                                                window,
 6374                                                cx
 6375                                            ))),
 6376
 6377                                        BottomDockLayout::LeftAligned => div()
 6378                                            .flex()
 6379                                            .flex_row()
 6380                                            .h_full()
 6381                                            .child(
 6382                                                div()
 6383                                                    .flex()
 6384                                                    .flex_col()
 6385                                                    .flex_1()
 6386                                                    .h_full()
 6387                                                    .child(
 6388                                                        div()
 6389                                                            .flex()
 6390                                                            .flex_row()
 6391                                                            .flex_1()
 6392                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 6393                                                            .child(
 6394                                                                div()
 6395                                                                    .flex()
 6396                                                                    .flex_col()
 6397                                                                    .flex_1()
 6398                                                                    .overflow_hidden()
 6399                                                                    .child(
 6400                                                                        h_flex()
 6401                                                                            .flex_1()
 6402                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6403                                                                            .child(self.center.render(
 6404                                                                                self.zoomed.as_ref(),
 6405                                                                                &PaneRenderContext {
 6406                                                                                    follower_states:
 6407                                                                                        &self.follower_states,
 6408                                                                                    active_call: self.active_call(),
 6409                                                                                    active_pane: &self.active_pane,
 6410                                                                                    app_state: &self.app_state,
 6411                                                                                    project: &self.project,
 6412                                                                                    workspace: &self.weak_self,
 6413                                                                                },
 6414                                                                                window,
 6415                                                                                cx,
 6416                                                                            ))
 6417                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6418                                                                    )
 6419                                                            )
 6420                                                    )
 6421                                                    .child(
 6422                                                        div()
 6423                                                            .w_full()
 6424                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6425                                                    ),
 6426                                            )
 6427                                            .children(self.render_dock(
 6428                                                DockPosition::Right,
 6429                                                &self.right_dock,
 6430                                                window,
 6431                                                cx,
 6432                                            )),
 6433
 6434                                        BottomDockLayout::RightAligned => div()
 6435                                            .flex()
 6436                                            .flex_row()
 6437                                            .h_full()
 6438                                            .children(self.render_dock(
 6439                                                DockPosition::Left,
 6440                                                &self.left_dock,
 6441                                                window,
 6442                                                cx,
 6443                                            ))
 6444                                            .child(
 6445                                                div()
 6446                                                    .flex()
 6447                                                    .flex_col()
 6448                                                    .flex_1()
 6449                                                    .h_full()
 6450                                                    .child(
 6451                                                        div()
 6452                                                            .flex()
 6453                                                            .flex_row()
 6454                                                            .flex_1()
 6455                                                            .child(
 6456                                                                div()
 6457                                                                    .flex()
 6458                                                                    .flex_col()
 6459                                                                    .flex_1()
 6460                                                                    .overflow_hidden()
 6461                                                                    .child(
 6462                                                                        h_flex()
 6463                                                                            .flex_1()
 6464                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6465                                                                            .child(self.center.render(
 6466                                                                                self.zoomed.as_ref(),
 6467                                                                                &PaneRenderContext {
 6468                                                                                    follower_states:
 6469                                                                                        &self.follower_states,
 6470                                                                                    active_call: self.active_call(),
 6471                                                                                    active_pane: &self.active_pane,
 6472                                                                                    app_state: &self.app_state,
 6473                                                                                    project: &self.project,
 6474                                                                                    workspace: &self.weak_self,
 6475                                                                                },
 6476                                                                                window,
 6477                                                                                cx,
 6478                                                                            ))
 6479                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6480                                                                    )
 6481                                                            )
 6482                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 6483                                                    )
 6484                                                    .child(
 6485                                                        div()
 6486                                                            .w_full()
 6487                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6488                                                    ),
 6489                                            ),
 6490
 6491                                        BottomDockLayout::Contained => div()
 6492                                            .flex()
 6493                                            .flex_row()
 6494                                            .h_full()
 6495                                            .children(self.render_dock(
 6496                                                DockPosition::Left,
 6497                                                &self.left_dock,
 6498                                                window,
 6499                                                cx,
 6500                                            ))
 6501                                            .child(
 6502                                                div()
 6503                                                    .flex()
 6504                                                    .flex_col()
 6505                                                    .flex_1()
 6506                                                    .overflow_hidden()
 6507                                                    .child(
 6508                                                        h_flex()
 6509                                                            .flex_1()
 6510                                                            .when_some(paddings.0, |this, p| {
 6511                                                                this.child(p.border_r_1())
 6512                                                            })
 6513                                                            .child(self.center.render(
 6514                                                                self.zoomed.as_ref(),
 6515                                                                &PaneRenderContext {
 6516                                                                    follower_states:
 6517                                                                        &self.follower_states,
 6518                                                                    active_call: self.active_call(),
 6519                                                                    active_pane: &self.active_pane,
 6520                                                                    app_state: &self.app_state,
 6521                                                                    project: &self.project,
 6522                                                                    workspace: &self.weak_self,
 6523                                                                },
 6524                                                                window,
 6525                                                                cx,
 6526                                                            ))
 6527                                                            .when_some(paddings.1, |this, p| {
 6528                                                                this.child(p.border_l_1())
 6529                                                            }),
 6530                                                    )
 6531                                                    .children(self.render_dock(
 6532                                                        DockPosition::Bottom,
 6533                                                        &self.bottom_dock,
 6534                                                        window,
 6535                                                        cx,
 6536                                                    )),
 6537                                            )
 6538                                            .children(self.render_dock(
 6539                                                DockPosition::Right,
 6540                                                &self.right_dock,
 6541                                                window,
 6542                                                cx,
 6543                                            )),
 6544                                    }
 6545                                })
 6546                                .children(self.zoomed.as_ref().and_then(|view| {
 6547                                    let zoomed_view = view.upgrade()?;
 6548                                    let div = div()
 6549                                        .occlude()
 6550                                        .absolute()
 6551                                        .overflow_hidden()
 6552                                        .border_color(colors.border)
 6553                                        .bg(colors.background)
 6554                                        .child(zoomed_view)
 6555                                        .inset_0()
 6556                                        .shadow_lg();
 6557
 6558                                    Some(match self.zoomed_position {
 6559                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 6560                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 6561                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 6562                                        None => {
 6563                                            div.top_2().bottom_2().left_2().right_2().border_1()
 6564                                        }
 6565                                    })
 6566                                }))
 6567                                .children(self.render_notifications(window, cx)),
 6568                        )
 6569                        .child(self.status_bar.clone())
 6570                        .child(self.modal_layer.clone())
 6571                        .child(self.toast_layer.clone()),
 6572                ),
 6573            window,
 6574            cx,
 6575        )
 6576    }
 6577}
 6578
 6579impl WorkspaceStore {
 6580    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 6581        Self {
 6582            workspaces: Default::default(),
 6583            _subscriptions: vec![
 6584                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 6585                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 6586            ],
 6587            client,
 6588        }
 6589    }
 6590
 6591    pub fn update_followers(
 6592        &self,
 6593        project_id: Option<u64>,
 6594        update: proto::update_followers::Variant,
 6595        cx: &App,
 6596    ) -> Option<()> {
 6597        let active_call = ActiveCall::try_global(cx)?;
 6598        let room_id = active_call.read(cx).room()?.read(cx).id();
 6599        self.client
 6600            .send(proto::UpdateFollowers {
 6601                room_id,
 6602                project_id,
 6603                variant: Some(update),
 6604            })
 6605            .log_err()
 6606    }
 6607
 6608    pub async fn handle_follow(
 6609        this: Entity<Self>,
 6610        envelope: TypedEnvelope<proto::Follow>,
 6611        mut cx: AsyncApp,
 6612    ) -> Result<proto::FollowResponse> {
 6613        this.update(&mut cx, |this, cx| {
 6614            let follower = Follower {
 6615                project_id: envelope.payload.project_id,
 6616                peer_id: envelope.original_sender_id()?,
 6617            };
 6618
 6619            let mut response = proto::FollowResponse::default();
 6620            this.workspaces.retain(|workspace| {
 6621                workspace
 6622                    .update(cx, |workspace, window, cx| {
 6623                        let handler_response =
 6624                            workspace.handle_follow(follower.project_id, window, cx);
 6625                        if let Some(active_view) = handler_response.active_view.clone() {
 6626                            if workspace.project.read(cx).remote_id() == follower.project_id {
 6627                                response.active_view = Some(active_view)
 6628                            }
 6629                        }
 6630                    })
 6631                    .is_ok()
 6632            });
 6633
 6634            Ok(response)
 6635        })?
 6636    }
 6637
 6638    async fn handle_update_followers(
 6639        this: Entity<Self>,
 6640        envelope: TypedEnvelope<proto::UpdateFollowers>,
 6641        mut cx: AsyncApp,
 6642    ) -> Result<()> {
 6643        let leader_id = envelope.original_sender_id()?;
 6644        let update = envelope.payload;
 6645
 6646        this.update(&mut cx, |this, cx| {
 6647            this.workspaces.retain(|workspace| {
 6648                workspace
 6649                    .update(cx, |workspace, window, cx| {
 6650                        let project_id = workspace.project.read(cx).remote_id();
 6651                        if update.project_id != project_id && update.project_id.is_some() {
 6652                            return;
 6653                        }
 6654                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 6655                    })
 6656                    .is_ok()
 6657            });
 6658            Ok(())
 6659        })?
 6660    }
 6661
 6662    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 6663        &self.workspaces
 6664    }
 6665}
 6666
 6667impl ViewId {
 6668    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 6669        Ok(Self {
 6670            creator: message
 6671                .creator
 6672                .map(CollaboratorId::PeerId)
 6673                .context("creator is missing")?,
 6674            id: message.id,
 6675        })
 6676    }
 6677
 6678    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 6679        if let CollaboratorId::PeerId(peer_id) = self.creator {
 6680            Some(proto::ViewId {
 6681                creator: Some(peer_id),
 6682                id: self.id,
 6683            })
 6684        } else {
 6685            None
 6686        }
 6687    }
 6688}
 6689
 6690impl FollowerState {
 6691    fn pane(&self) -> &Entity<Pane> {
 6692        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 6693    }
 6694}
 6695
 6696pub trait WorkspaceHandle {
 6697    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 6698}
 6699
 6700impl WorkspaceHandle for Entity<Workspace> {
 6701    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 6702        self.read(cx)
 6703            .worktrees(cx)
 6704            .flat_map(|worktree| {
 6705                let worktree_id = worktree.read(cx).id();
 6706                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 6707                    worktree_id,
 6708                    path: f.path.clone(),
 6709                })
 6710            })
 6711            .collect::<Vec<_>>()
 6712    }
 6713}
 6714
 6715impl std::fmt::Debug for OpenPaths {
 6716    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 6717        f.debug_struct("OpenPaths")
 6718            .field("paths", &self.paths)
 6719            .finish()
 6720    }
 6721}
 6722
 6723pub async fn last_opened_workspace_location() -> Option<SerializedWorkspaceLocation> {
 6724    DB.last_workspace().await.log_err().flatten()
 6725}
 6726
 6727pub fn last_session_workspace_locations(
 6728    last_session_id: &str,
 6729    last_session_window_stack: Option<Vec<WindowId>>,
 6730) -> Option<Vec<SerializedWorkspaceLocation>> {
 6731    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 6732        .log_err()
 6733}
 6734
 6735actions!(
 6736    collab,
 6737    [
 6738        /// Opens the channel notes for the current call.
 6739        ///
 6740        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 6741        /// can be copied via "Copy link to section" in the context menu of the channel notes
 6742        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 6743        OpenChannelNotes,
 6744        /// Mutes your microphone.
 6745        Mute,
 6746        /// Deafens yourself (mute both microphone and speakers).
 6747        Deafen,
 6748        /// Leaves the current call.
 6749        LeaveCall,
 6750        /// Shares the current project with collaborators.
 6751        ShareProject,
 6752        /// Shares your screen with collaborators.
 6753        ScreenShare
 6754    ]
 6755);
 6756actions!(
 6757    zed,
 6758    [
 6759        /// Opens the Zed log file.
 6760        OpenLog
 6761    ]
 6762);
 6763
 6764async fn join_channel_internal(
 6765    channel_id: ChannelId,
 6766    app_state: &Arc<AppState>,
 6767    requesting_window: Option<WindowHandle<Workspace>>,
 6768    active_call: &Entity<ActiveCall>,
 6769    cx: &mut AsyncApp,
 6770) -> Result<bool> {
 6771    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 6772        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 6773            return (false, None);
 6774        };
 6775
 6776        let already_in_channel = room.channel_id() == Some(channel_id);
 6777        let should_prompt = room.is_sharing_project()
 6778            && !room.remote_participants().is_empty()
 6779            && !already_in_channel;
 6780        let open_room = if already_in_channel {
 6781            active_call.room().cloned()
 6782        } else {
 6783            None
 6784        };
 6785        (should_prompt, open_room)
 6786    })?;
 6787
 6788    if let Some(room) = open_room {
 6789        let task = room.update(cx, |room, cx| {
 6790            if let Some((project, host)) = room.most_active_project(cx) {
 6791                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 6792            }
 6793
 6794            None
 6795        })?;
 6796        if let Some(task) = task {
 6797            task.await?;
 6798        }
 6799        return anyhow::Ok(true);
 6800    }
 6801
 6802    if should_prompt {
 6803        if let Some(workspace) = requesting_window {
 6804            let answer = workspace
 6805                .update(cx, |_, window, cx| {
 6806                    window.prompt(
 6807                        PromptLevel::Warning,
 6808                        "Do you want to switch channels?",
 6809                        Some("Leaving this call will unshare your current project."),
 6810                        &["Yes, Join Channel", "Cancel"],
 6811                        cx,
 6812                    )
 6813                })?
 6814                .await;
 6815
 6816            if answer == Ok(1) {
 6817                return Ok(false);
 6818            }
 6819        } else {
 6820            return Ok(false); // unreachable!() hopefully
 6821        }
 6822    }
 6823
 6824    let client = cx.update(|cx| active_call.read(cx).client())?;
 6825
 6826    let mut client_status = client.status();
 6827
 6828    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 6829    'outer: loop {
 6830        let Some(status) = client_status.recv().await else {
 6831            anyhow::bail!("error connecting");
 6832        };
 6833
 6834        match status {
 6835            Status::Connecting
 6836            | Status::Authenticating
 6837            | Status::Reconnecting
 6838            | Status::Reauthenticating => continue,
 6839            Status::Connected { .. } => break 'outer,
 6840            Status::SignedOut => return Err(ErrorCode::SignedOut.into()),
 6841            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 6842            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 6843                return Err(ErrorCode::Disconnected.into());
 6844            }
 6845        }
 6846    }
 6847
 6848    let room = active_call
 6849        .update(cx, |active_call, cx| {
 6850            active_call.join_channel(channel_id, cx)
 6851        })?
 6852        .await?;
 6853
 6854    let Some(room) = room else {
 6855        return anyhow::Ok(true);
 6856    };
 6857
 6858    room.update(cx, |room, _| room.room_update_completed())?
 6859        .await;
 6860
 6861    let task = room.update(cx, |room, cx| {
 6862        if let Some((project, host)) = room.most_active_project(cx) {
 6863            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 6864        }
 6865
 6866        // If you are the first to join a channel, see if you should share your project.
 6867        if room.remote_participants().is_empty() && !room.local_participant_is_guest() {
 6868            if let Some(workspace) = requesting_window {
 6869                let project = workspace.update(cx, |workspace, _, cx| {
 6870                    let project = workspace.project.read(cx);
 6871
 6872                    if !CallSettings::get_global(cx).share_on_join {
 6873                        return None;
 6874                    }
 6875
 6876                    if (project.is_local() || project.is_via_ssh())
 6877                        && project.visible_worktrees(cx).any(|tree| {
 6878                            tree.read(cx)
 6879                                .root_entry()
 6880                                .map_or(false, |entry| entry.is_dir())
 6881                        })
 6882                    {
 6883                        Some(workspace.project.clone())
 6884                    } else {
 6885                        None
 6886                    }
 6887                });
 6888                if let Ok(Some(project)) = project {
 6889                    return Some(cx.spawn(async move |room, cx| {
 6890                        room.update(cx, |room, cx| room.share_project(project, cx))?
 6891                            .await?;
 6892                        Ok(())
 6893                    }));
 6894                }
 6895            }
 6896        }
 6897
 6898        None
 6899    })?;
 6900    if let Some(task) = task {
 6901        task.await?;
 6902        return anyhow::Ok(true);
 6903    }
 6904    anyhow::Ok(false)
 6905}
 6906
 6907pub fn join_channel(
 6908    channel_id: ChannelId,
 6909    app_state: Arc<AppState>,
 6910    requesting_window: Option<WindowHandle<Workspace>>,
 6911    cx: &mut App,
 6912) -> Task<Result<()>> {
 6913    let active_call = ActiveCall::global(cx);
 6914    cx.spawn(async move |cx| {
 6915        let result = join_channel_internal(
 6916            channel_id,
 6917            &app_state,
 6918            requesting_window,
 6919            &active_call,
 6920             cx,
 6921        )
 6922            .await;
 6923
 6924        // join channel succeeded, and opened a window
 6925        if matches!(result, Ok(true)) {
 6926            return anyhow::Ok(());
 6927        }
 6928
 6929        // find an existing workspace to focus and show call controls
 6930        let mut active_window =
 6931            requesting_window.or_else(|| activate_any_workspace_window( cx));
 6932        if active_window.is_none() {
 6933            // no open workspaces, make one to show the error in (blergh)
 6934            let (window_handle, _) = cx
 6935                .update(|cx| {
 6936                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 6937                })?
 6938                .await?;
 6939
 6940            if result.is_ok() {
 6941                cx.update(|cx| {
 6942                    cx.dispatch_action(&OpenChannelNotes);
 6943                }).log_err();
 6944            }
 6945
 6946            active_window = Some(window_handle);
 6947        }
 6948
 6949        if let Err(err) = result {
 6950            log::error!("failed to join channel: {}", err);
 6951            if let Some(active_window) = active_window {
 6952                active_window
 6953                    .update(cx, |_, window, cx| {
 6954                        let detail: SharedString = match err.error_code() {
 6955                            ErrorCode::SignedOut => {
 6956                                "Please sign in to continue.".into()
 6957                            }
 6958                            ErrorCode::UpgradeRequired => {
 6959                                "Your are running an unsupported version of Zed. Please update to continue.".into()
 6960                            }
 6961                            ErrorCode::NoSuchChannel => {
 6962                                "No matching channel was found. Please check the link and try again.".into()
 6963                            }
 6964                            ErrorCode::Forbidden => {
 6965                                "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
 6966                            }
 6967                            ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
 6968                            _ => format!("{}\n\nPlease try again.", err).into(),
 6969                        };
 6970                        window.prompt(
 6971                            PromptLevel::Critical,
 6972                            "Failed to join channel",
 6973                            Some(&detail),
 6974                            &["Ok"],
 6975                        cx)
 6976                    })?
 6977                    .await
 6978                    .ok();
 6979            }
 6980        }
 6981
 6982        // return ok, we showed the error to the user.
 6983        anyhow::Ok(())
 6984    })
 6985}
 6986
 6987pub async fn get_any_active_workspace(
 6988    app_state: Arc<AppState>,
 6989    mut cx: AsyncApp,
 6990) -> anyhow::Result<WindowHandle<Workspace>> {
 6991    // find an existing workspace to focus and show call controls
 6992    let active_window = activate_any_workspace_window(&mut cx);
 6993    if active_window.is_none() {
 6994        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 6995            .await?;
 6996    }
 6997    activate_any_workspace_window(&mut cx).context("could not open zed")
 6998}
 6999
 7000fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7001    cx.update(|cx| {
 7002        if let Some(workspace_window) = cx
 7003            .active_window()
 7004            .and_then(|window| window.downcast::<Workspace>())
 7005        {
 7006            return Some(workspace_window);
 7007        }
 7008
 7009        for window in cx.windows() {
 7010            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7011                workspace_window
 7012                    .update(cx, |_, window, _| window.activate_window())
 7013                    .ok();
 7014                return Some(workspace_window);
 7015            }
 7016        }
 7017        None
 7018    })
 7019    .ok()
 7020    .flatten()
 7021}
 7022
 7023pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7024    cx.windows()
 7025        .into_iter()
 7026        .filter_map(|window| window.downcast::<Workspace>())
 7027        .filter(|workspace| {
 7028            workspace
 7029                .read(cx)
 7030                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7031        })
 7032        .collect()
 7033}
 7034
 7035#[derive(Default)]
 7036pub struct OpenOptions {
 7037    pub visible: Option<OpenVisible>,
 7038    pub focus: Option<bool>,
 7039    pub open_new_workspace: Option<bool>,
 7040    pub replace_window: Option<WindowHandle<Workspace>>,
 7041    pub env: Option<HashMap<String, String>>,
 7042}
 7043
 7044#[allow(clippy::type_complexity)]
 7045pub fn open_paths(
 7046    abs_paths: &[PathBuf],
 7047    app_state: Arc<AppState>,
 7048    open_options: OpenOptions,
 7049    cx: &mut App,
 7050) -> Task<
 7051    anyhow::Result<(
 7052        WindowHandle<Workspace>,
 7053        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7054    )>,
 7055> {
 7056    let abs_paths = abs_paths.to_vec();
 7057    let mut existing = None;
 7058    let mut best_match = None;
 7059    let mut open_visible = OpenVisible::All;
 7060
 7061    cx.spawn(async move |cx| {
 7062        if open_options.open_new_workspace != Some(true) {
 7063            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7064            let all_metadatas = futures::future::join_all(all_paths)
 7065                .await
 7066                .into_iter()
 7067                .filter_map(|result| result.ok().flatten())
 7068                .collect::<Vec<_>>();
 7069
 7070            cx.update(|cx| {
 7071                for window in local_workspace_windows(&cx) {
 7072                    if let Ok(workspace) = window.read(&cx) {
 7073                        let m = workspace.project.read(&cx).visibility_for_paths(
 7074                            &abs_paths,
 7075                            &all_metadatas,
 7076                            open_options.open_new_workspace == None,
 7077                            cx,
 7078                        );
 7079                        if m > best_match {
 7080                            existing = Some(window);
 7081                            best_match = m;
 7082                        } else if best_match.is_none()
 7083                            && open_options.open_new_workspace == Some(false)
 7084                        {
 7085                            existing = Some(window)
 7086                        }
 7087                    }
 7088                }
 7089            })?;
 7090
 7091            if open_options.open_new_workspace.is_none() && existing.is_none() {
 7092                if all_metadatas.iter().all(|file| !file.is_dir) {
 7093                    cx.update(|cx| {
 7094                        if let Some(window) = cx
 7095                            .active_window()
 7096                            .and_then(|window| window.downcast::<Workspace>())
 7097                        {
 7098                            if let Ok(workspace) = window.read(cx) {
 7099                                let project = workspace.project().read(cx);
 7100                                if project.is_local() && !project.is_via_collab() {
 7101                                    existing = Some(window);
 7102                                    open_visible = OpenVisible::None;
 7103                                    return;
 7104                                }
 7105                            }
 7106                        }
 7107                        for window in local_workspace_windows(cx) {
 7108                            if let Ok(workspace) = window.read(cx) {
 7109                                let project = workspace.project().read(cx);
 7110                                if project.is_via_collab() {
 7111                                    continue;
 7112                                }
 7113                                existing = Some(window);
 7114                                open_visible = OpenVisible::None;
 7115                                break;
 7116                            }
 7117                        }
 7118                    })?;
 7119                }
 7120            }
 7121        }
 7122
 7123        if let Some(existing) = existing {
 7124            let open_task = existing
 7125                .update(cx, |workspace, window, cx| {
 7126                    window.activate_window();
 7127                    workspace.open_paths(
 7128                        abs_paths,
 7129                        OpenOptions {
 7130                            visible: Some(open_visible),
 7131                            ..Default::default()
 7132                        },
 7133                        None,
 7134                        window,
 7135                        cx,
 7136                    )
 7137                })?
 7138                .await;
 7139
 7140            _ = existing.update(cx, |workspace, _, cx| {
 7141                for item in open_task.iter().flatten() {
 7142                    if let Err(e) = item {
 7143                        workspace.show_error(&e, cx);
 7144                    }
 7145                }
 7146            });
 7147
 7148            Ok((existing, open_task))
 7149        } else {
 7150            cx.update(move |cx| {
 7151                Workspace::new_local(
 7152                    abs_paths,
 7153                    app_state.clone(),
 7154                    open_options.replace_window,
 7155                    open_options.env,
 7156                    cx,
 7157                )
 7158            })?
 7159            .await
 7160        }
 7161    })
 7162}
 7163
 7164pub fn open_new(
 7165    open_options: OpenOptions,
 7166    app_state: Arc<AppState>,
 7167    cx: &mut App,
 7168    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7169) -> Task<anyhow::Result<()>> {
 7170    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7171    cx.spawn(async move |cx| {
 7172        let (workspace, opened_paths) = task.await?;
 7173        workspace.update(cx, |workspace, window, cx| {
 7174            if opened_paths.is_empty() {
 7175                init(workspace, window, cx)
 7176            }
 7177        })?;
 7178        Ok(())
 7179    })
 7180}
 7181
 7182pub fn create_and_open_local_file(
 7183    path: &'static Path,
 7184    window: &mut Window,
 7185    cx: &mut Context<Workspace>,
 7186    default_content: impl 'static + Send + FnOnce() -> Rope,
 7187) -> Task<Result<Box<dyn ItemHandle>>> {
 7188    cx.spawn_in(window, async move |workspace, cx| {
 7189        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7190        if !fs.is_file(path).await {
 7191            fs.create_file(path, Default::default()).await?;
 7192            fs.save(path, &default_content(), Default::default())
 7193                .await?;
 7194        }
 7195
 7196        let mut items = workspace
 7197            .update_in(cx, |workspace, window, cx| {
 7198                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7199                    workspace.open_paths(
 7200                        vec![path.to_path_buf()],
 7201                        OpenOptions {
 7202                            visible: Some(OpenVisible::None),
 7203                            ..Default::default()
 7204                        },
 7205                        None,
 7206                        window,
 7207                        cx,
 7208                    )
 7209                })
 7210            })?
 7211            .await?
 7212            .await;
 7213
 7214        let item = items.pop().flatten();
 7215        item.with_context(|| format!("path {path:?} is not a file"))?
 7216    })
 7217}
 7218
 7219pub fn open_ssh_project_with_new_connection(
 7220    window: WindowHandle<Workspace>,
 7221    connection_options: SshConnectionOptions,
 7222    cancel_rx: oneshot::Receiver<()>,
 7223    delegate: Arc<dyn SshClientDelegate>,
 7224    app_state: Arc<AppState>,
 7225    paths: Vec<PathBuf>,
 7226    cx: &mut App,
 7227) -> Task<Result<()>> {
 7228    cx.spawn(async move |cx| {
 7229        let (serialized_ssh_project, workspace_id, serialized_workspace) =
 7230            serialize_ssh_project(connection_options.clone(), paths.clone(), &cx).await?;
 7231
 7232        let session = match cx
 7233            .update(|cx| {
 7234                remote::SshRemoteClient::new(
 7235                    ConnectionIdentifier::Workspace(workspace_id.0),
 7236                    connection_options,
 7237                    cancel_rx,
 7238                    delegate,
 7239                    cx,
 7240                )
 7241            })?
 7242            .await?
 7243        {
 7244            Some(result) => result,
 7245            None => return Ok(()),
 7246        };
 7247
 7248        let project = cx.update(|cx| {
 7249            project::Project::ssh(
 7250                session,
 7251                app_state.client.clone(),
 7252                app_state.node_runtime.clone(),
 7253                app_state.user_store.clone(),
 7254                app_state.languages.clone(),
 7255                app_state.fs.clone(),
 7256                cx,
 7257            )
 7258        })?;
 7259
 7260        open_ssh_project_inner(
 7261            project,
 7262            paths,
 7263            serialized_ssh_project,
 7264            workspace_id,
 7265            serialized_workspace,
 7266            app_state,
 7267            window,
 7268            cx,
 7269        )
 7270        .await
 7271    })
 7272}
 7273
 7274pub fn open_ssh_project_with_existing_connection(
 7275    connection_options: SshConnectionOptions,
 7276    project: Entity<Project>,
 7277    paths: Vec<PathBuf>,
 7278    app_state: Arc<AppState>,
 7279    window: WindowHandle<Workspace>,
 7280    cx: &mut AsyncApp,
 7281) -> Task<Result<()>> {
 7282    cx.spawn(async move |cx| {
 7283        let (serialized_ssh_project, workspace_id, serialized_workspace) =
 7284            serialize_ssh_project(connection_options.clone(), paths.clone(), &cx).await?;
 7285
 7286        open_ssh_project_inner(
 7287            project,
 7288            paths,
 7289            serialized_ssh_project,
 7290            workspace_id,
 7291            serialized_workspace,
 7292            app_state,
 7293            window,
 7294            cx,
 7295        )
 7296        .await
 7297    })
 7298}
 7299
 7300async fn open_ssh_project_inner(
 7301    project: Entity<Project>,
 7302    paths: Vec<PathBuf>,
 7303    serialized_ssh_project: SerializedSshProject,
 7304    workspace_id: WorkspaceId,
 7305    serialized_workspace: Option<SerializedWorkspace>,
 7306    app_state: Arc<AppState>,
 7307    window: WindowHandle<Workspace>,
 7308    cx: &mut AsyncApp,
 7309) -> Result<()> {
 7310    let toolchains = DB.toolchains(workspace_id).await?;
 7311    for (toolchain, worktree_id, path) in toolchains {
 7312        project
 7313            .update(cx, |this, cx| {
 7314                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7315            })?
 7316            .await;
 7317    }
 7318    let mut project_paths_to_open = vec![];
 7319    let mut project_path_errors = vec![];
 7320
 7321    for path in paths {
 7322        let result = cx
 7323            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7324            .await;
 7325        match result {
 7326            Ok((_, project_path)) => {
 7327                project_paths_to_open.push((path.clone(), Some(project_path)));
 7328            }
 7329            Err(error) => {
 7330                project_path_errors.push(error);
 7331            }
 7332        };
 7333    }
 7334
 7335    if project_paths_to_open.is_empty() {
 7336        return Err(project_path_errors.pop().context("no paths given")?);
 7337    }
 7338
 7339    cx.update_window(window.into(), |_, window, cx| {
 7340        window.replace_root(cx, |window, cx| {
 7341            telemetry::event!("SSH Project Opened");
 7342
 7343            let mut workspace =
 7344                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7345            workspace.set_serialized_ssh_project(serialized_ssh_project);
 7346            workspace.update_history(cx);
 7347
 7348            if let Some(ref serialized) = serialized_workspace {
 7349                workspace.centered_layout = serialized.centered_layout;
 7350            }
 7351
 7352            workspace
 7353        });
 7354    })?;
 7355
 7356    window
 7357        .update(cx, |_, window, cx| {
 7358            window.activate_window();
 7359            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7360        })?
 7361        .await?;
 7362
 7363    window.update(cx, |workspace, _, cx| {
 7364        for error in project_path_errors {
 7365            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7366                if let Some(path) = error.error_tag("path") {
 7367                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7368                }
 7369            } else {
 7370                workspace.show_error(&error, cx)
 7371            }
 7372        }
 7373    })?;
 7374
 7375    Ok(())
 7376}
 7377
 7378fn serialize_ssh_project(
 7379    connection_options: SshConnectionOptions,
 7380    paths: Vec<PathBuf>,
 7381    cx: &AsyncApp,
 7382) -> Task<
 7383    Result<(
 7384        SerializedSshProject,
 7385        WorkspaceId,
 7386        Option<SerializedWorkspace>,
 7387    )>,
 7388> {
 7389    cx.background_spawn(async move {
 7390        let serialized_ssh_project = persistence::DB
 7391            .get_or_create_ssh_project(
 7392                connection_options.host.clone(),
 7393                connection_options.port,
 7394                paths
 7395                    .iter()
 7396                    .map(|path| path.to_string_lossy().to_string())
 7397                    .collect::<Vec<_>>(),
 7398                connection_options.username.clone(),
 7399            )
 7400            .await?;
 7401
 7402        let serialized_workspace =
 7403            persistence::DB.workspace_for_ssh_project(&serialized_ssh_project);
 7404
 7405        let workspace_id = if let Some(workspace_id) =
 7406            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7407        {
 7408            workspace_id
 7409        } else {
 7410            persistence::DB.next_id().await?
 7411        };
 7412
 7413        Ok((serialized_ssh_project, workspace_id, serialized_workspace))
 7414    })
 7415}
 7416
 7417pub fn join_in_room_project(
 7418    project_id: u64,
 7419    follow_user_id: u64,
 7420    app_state: Arc<AppState>,
 7421    cx: &mut App,
 7422) -> Task<Result<()>> {
 7423    let windows = cx.windows();
 7424    cx.spawn(async move |cx| {
 7425        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7426            window_handle
 7427                .downcast::<Workspace>()
 7428                .and_then(|window_handle| {
 7429                    window_handle
 7430                        .update(cx, |workspace, _window, cx| {
 7431                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7432                                Some(window_handle)
 7433                            } else {
 7434                                None
 7435                            }
 7436                        })
 7437                        .unwrap_or(None)
 7438                })
 7439        });
 7440
 7441        let workspace = if let Some(existing_workspace) = existing_workspace {
 7442            existing_workspace
 7443        } else {
 7444            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7445            let room = active_call
 7446                .read_with(cx, |call, _| call.room().cloned())?
 7447                .context("not in a call")?;
 7448            let project = room
 7449                .update(cx, |room, cx| {
 7450                    room.join_project(
 7451                        project_id,
 7452                        app_state.languages.clone(),
 7453                        app_state.fs.clone(),
 7454                        cx,
 7455                    )
 7456                })?
 7457                .await?;
 7458
 7459            let window_bounds_override = window_bounds_env_override();
 7460            cx.update(|cx| {
 7461                let mut options = (app_state.build_window_options)(None, cx);
 7462                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7463                cx.open_window(options, |window, cx| {
 7464                    cx.new(|cx| {
 7465                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7466                    })
 7467                })
 7468            })??
 7469        };
 7470
 7471        workspace.update(cx, |workspace, window, cx| {
 7472            cx.activate(true);
 7473            window.activate_window();
 7474
 7475            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7476                let follow_peer_id = room
 7477                    .read(cx)
 7478                    .remote_participants()
 7479                    .iter()
 7480                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7481                    .map(|(_, p)| p.peer_id)
 7482                    .or_else(|| {
 7483                        // If we couldn't follow the given user, follow the host instead.
 7484                        let collaborator = workspace
 7485                            .project()
 7486                            .read(cx)
 7487                            .collaborators()
 7488                            .values()
 7489                            .find(|collaborator| collaborator.is_host)?;
 7490                        Some(collaborator.peer_id)
 7491                    });
 7492
 7493                if let Some(follow_peer_id) = follow_peer_id {
 7494                    workspace.follow(follow_peer_id, window, cx);
 7495                }
 7496            }
 7497        })?;
 7498
 7499        anyhow::Ok(())
 7500    })
 7501}
 7502
 7503pub fn reload(reload: &Reload, cx: &mut App) {
 7504    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7505    let mut workspace_windows = cx
 7506        .windows()
 7507        .into_iter()
 7508        .filter_map(|window| window.downcast::<Workspace>())
 7509        .collect::<Vec<_>>();
 7510
 7511    // If multiple windows have unsaved changes, and need a save prompt,
 7512    // prompt in the active window before switching to a different window.
 7513    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7514
 7515    let mut prompt = None;
 7516    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7517        prompt = window
 7518            .update(cx, |_, window, cx| {
 7519                window.prompt(
 7520                    PromptLevel::Info,
 7521                    "Are you sure you want to restart?",
 7522                    None,
 7523                    &["Restart", "Cancel"],
 7524                    cx,
 7525                )
 7526            })
 7527            .ok();
 7528    }
 7529
 7530    let binary_path = reload.binary_path.clone();
 7531    cx.spawn(async move |cx| {
 7532        if let Some(prompt) = prompt {
 7533            let answer = prompt.await?;
 7534            if answer != 0 {
 7535                return Ok(());
 7536            }
 7537        }
 7538
 7539        // If the user cancels any save prompt, then keep the app open.
 7540        for window in workspace_windows {
 7541            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7542                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7543            }) {
 7544                if !should_close.await? {
 7545                    return Ok(());
 7546                }
 7547            }
 7548        }
 7549
 7550        cx.update(|cx| cx.restart(binary_path))
 7551    })
 7552    .detach_and_log_err(cx);
 7553}
 7554
 7555fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7556    let mut parts = value.split(',');
 7557    let x: usize = parts.next()?.parse().ok()?;
 7558    let y: usize = parts.next()?.parse().ok()?;
 7559    Some(point(px(x as f32), px(y as f32)))
 7560}
 7561
 7562fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7563    let mut parts = value.split(',');
 7564    let width: usize = parts.next()?.parse().ok()?;
 7565    let height: usize = parts.next()?.parse().ok()?;
 7566    Some(size(px(width as f32), px(height as f32)))
 7567}
 7568
 7569/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7570pub fn client_side_decorations(
 7571    element: impl IntoElement,
 7572    window: &mut Window,
 7573    cx: &mut App,
 7574) -> Stateful<Div> {
 7575    const BORDER_SIZE: Pixels = px(1.0);
 7576    let decorations = window.window_decorations();
 7577
 7578    match decorations {
 7579        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7580        Decorations::Server { .. } => window.set_client_inset(px(0.0)),
 7581    }
 7582
 7583    struct GlobalResizeEdge(ResizeEdge);
 7584    impl Global for GlobalResizeEdge {}
 7585
 7586    div()
 7587        .id("window-backdrop")
 7588        .bg(transparent_black())
 7589        .map(|div| match decorations {
 7590            Decorations::Server => div,
 7591            Decorations::Client { tiling, .. } => div
 7592                .when(!(tiling.top || tiling.right), |div| {
 7593                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7594                })
 7595                .when(!(tiling.top || tiling.left), |div| {
 7596                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7597                })
 7598                .when(!(tiling.bottom || tiling.right), |div| {
 7599                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7600                })
 7601                .when(!(tiling.bottom || tiling.left), |div| {
 7602                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7603                })
 7604                .when(!tiling.top, |div| {
 7605                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7606                })
 7607                .when(!tiling.bottom, |div| {
 7608                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7609                })
 7610                .when(!tiling.left, |div| {
 7611                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7612                })
 7613                .when(!tiling.right, |div| {
 7614                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7615                })
 7616                .on_mouse_move(move |e, window, cx| {
 7617                    let size = window.window_bounds().get_bounds().size;
 7618                    let pos = e.position;
 7619
 7620                    let new_edge =
 7621                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 7622
 7623                    let edge = cx.try_global::<GlobalResizeEdge>();
 7624                    if new_edge != edge.map(|edge| edge.0) {
 7625                        window
 7626                            .window_handle()
 7627                            .update(cx, |workspace, _, cx| {
 7628                                cx.notify(workspace.entity_id());
 7629                            })
 7630                            .ok();
 7631                    }
 7632                })
 7633                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 7634                    let size = window.window_bounds().get_bounds().size;
 7635                    let pos = e.position;
 7636
 7637                    let edge = match resize_edge(
 7638                        pos,
 7639                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 7640                        size,
 7641                        tiling,
 7642                    ) {
 7643                        Some(value) => value,
 7644                        None => return,
 7645                    };
 7646
 7647                    window.start_window_resize(edge);
 7648                }),
 7649        })
 7650        .size_full()
 7651        .child(
 7652            div()
 7653                .cursor(CursorStyle::Arrow)
 7654                .map(|div| match decorations {
 7655                    Decorations::Server => div,
 7656                    Decorations::Client { tiling } => div
 7657                        .border_color(cx.theme().colors().border)
 7658                        .when(!(tiling.top || tiling.right), |div| {
 7659                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7660                        })
 7661                        .when(!(tiling.top || tiling.left), |div| {
 7662                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7663                        })
 7664                        .when(!(tiling.bottom || tiling.right), |div| {
 7665                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7666                        })
 7667                        .when(!(tiling.bottom || tiling.left), |div| {
 7668                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7669                        })
 7670                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 7671                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 7672                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 7673                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 7674                        .when(!tiling.is_tiled(), |div| {
 7675                            div.shadow(vec![gpui::BoxShadow {
 7676                                color: Hsla {
 7677                                    h: 0.,
 7678                                    s: 0.,
 7679                                    l: 0.,
 7680                                    a: 0.4,
 7681                                },
 7682                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 7683                                spread_radius: px(0.),
 7684                                offset: point(px(0.0), px(0.0)),
 7685                            }])
 7686                        }),
 7687                })
 7688                .on_mouse_move(|_e, _, cx| {
 7689                    cx.stop_propagation();
 7690                })
 7691                .size_full()
 7692                .child(element),
 7693        )
 7694        .map(|div| match decorations {
 7695            Decorations::Server => div,
 7696            Decorations::Client { tiling, .. } => div.child(
 7697                canvas(
 7698                    |_bounds, window, _| {
 7699                        window.insert_hitbox(
 7700                            Bounds::new(
 7701                                point(px(0.0), px(0.0)),
 7702                                window.window_bounds().get_bounds().size,
 7703                            ),
 7704                            HitboxBehavior::Normal,
 7705                        )
 7706                    },
 7707                    move |_bounds, hitbox, window, cx| {
 7708                        let mouse = window.mouse_position();
 7709                        let size = window.window_bounds().get_bounds().size;
 7710                        let Some(edge) =
 7711                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 7712                        else {
 7713                            return;
 7714                        };
 7715                        cx.set_global(GlobalResizeEdge(edge));
 7716                        window.set_cursor_style(
 7717                            match edge {
 7718                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 7719                                ResizeEdge::Left | ResizeEdge::Right => {
 7720                                    CursorStyle::ResizeLeftRight
 7721                                }
 7722                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 7723                                    CursorStyle::ResizeUpLeftDownRight
 7724                                }
 7725                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 7726                                    CursorStyle::ResizeUpRightDownLeft
 7727                                }
 7728                            },
 7729                            &hitbox,
 7730                        );
 7731                    },
 7732                )
 7733                .size_full()
 7734                .absolute(),
 7735            ),
 7736        })
 7737}
 7738
 7739fn resize_edge(
 7740    pos: Point<Pixels>,
 7741    shadow_size: Pixels,
 7742    window_size: Size<Pixels>,
 7743    tiling: Tiling,
 7744) -> Option<ResizeEdge> {
 7745    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 7746    if bounds.contains(&pos) {
 7747        return None;
 7748    }
 7749
 7750    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 7751    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 7752    if !tiling.top && top_left_bounds.contains(&pos) {
 7753        return Some(ResizeEdge::TopLeft);
 7754    }
 7755
 7756    let top_right_bounds = Bounds::new(
 7757        Point::new(window_size.width - corner_size.width, px(0.)),
 7758        corner_size,
 7759    );
 7760    if !tiling.top && top_right_bounds.contains(&pos) {
 7761        return Some(ResizeEdge::TopRight);
 7762    }
 7763
 7764    let bottom_left_bounds = Bounds::new(
 7765        Point::new(px(0.), window_size.height - corner_size.height),
 7766        corner_size,
 7767    );
 7768    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 7769        return Some(ResizeEdge::BottomLeft);
 7770    }
 7771
 7772    let bottom_right_bounds = Bounds::new(
 7773        Point::new(
 7774            window_size.width - corner_size.width,
 7775            window_size.height - corner_size.height,
 7776        ),
 7777        corner_size,
 7778    );
 7779    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 7780        return Some(ResizeEdge::BottomRight);
 7781    }
 7782
 7783    if !tiling.top && pos.y < shadow_size {
 7784        Some(ResizeEdge::Top)
 7785    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 7786        Some(ResizeEdge::Bottom)
 7787    } else if !tiling.left && pos.x < shadow_size {
 7788        Some(ResizeEdge::Left)
 7789    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 7790        Some(ResizeEdge::Right)
 7791    } else {
 7792        None
 7793    }
 7794}
 7795
 7796fn join_pane_into_active(
 7797    active_pane: &Entity<Pane>,
 7798    pane: &Entity<Pane>,
 7799    window: &mut Window,
 7800    cx: &mut App,
 7801) {
 7802    if pane == active_pane {
 7803        return;
 7804    } else if pane.read(cx).items_len() == 0 {
 7805        pane.update(cx, |_, cx| {
 7806            cx.emit(pane::Event::Remove {
 7807                focus_on_pane: None,
 7808            });
 7809        })
 7810    } else {
 7811        move_all_items(pane, active_pane, window, cx);
 7812    }
 7813}
 7814
 7815fn move_all_items(
 7816    from_pane: &Entity<Pane>,
 7817    to_pane: &Entity<Pane>,
 7818    window: &mut Window,
 7819    cx: &mut App,
 7820) {
 7821    let destination_is_different = from_pane != to_pane;
 7822    let mut moved_items = 0;
 7823    for (item_ix, item_handle) in from_pane
 7824        .read(cx)
 7825        .items()
 7826        .enumerate()
 7827        .map(|(ix, item)| (ix, item.clone()))
 7828        .collect::<Vec<_>>()
 7829    {
 7830        let ix = item_ix - moved_items;
 7831        if destination_is_different {
 7832            // Close item from previous pane
 7833            from_pane.update(cx, |source, cx| {
 7834                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 7835            });
 7836            moved_items += 1;
 7837        }
 7838
 7839        // This automatically removes duplicate items in the pane
 7840        to_pane.update(cx, |destination, cx| {
 7841            destination.add_item(item_handle, true, true, None, window, cx);
 7842            window.focus(&destination.focus_handle(cx))
 7843        });
 7844    }
 7845}
 7846
 7847pub fn move_item(
 7848    source: &Entity<Pane>,
 7849    destination: &Entity<Pane>,
 7850    item_id_to_move: EntityId,
 7851    destination_index: usize,
 7852    activate: bool,
 7853    window: &mut Window,
 7854    cx: &mut App,
 7855) {
 7856    let Some((item_ix, item_handle)) = source
 7857        .read(cx)
 7858        .items()
 7859        .enumerate()
 7860        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 7861        .map(|(ix, item)| (ix, item.clone()))
 7862    else {
 7863        // Tab was closed during drag
 7864        return;
 7865    };
 7866
 7867    if source != destination {
 7868        // Close item from previous pane
 7869        source.update(cx, |source, cx| {
 7870            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 7871        });
 7872    }
 7873
 7874    // This automatically removes duplicate items in the pane
 7875    destination.update(cx, |destination, cx| {
 7876        destination.add_item_inner(
 7877            item_handle,
 7878            activate,
 7879            activate,
 7880            activate,
 7881            Some(destination_index),
 7882            window,
 7883            cx,
 7884        );
 7885        if activate {
 7886            window.focus(&destination.focus_handle(cx))
 7887        }
 7888    });
 7889}
 7890
 7891pub fn move_active_item(
 7892    source: &Entity<Pane>,
 7893    destination: &Entity<Pane>,
 7894    focus_destination: bool,
 7895    close_if_empty: bool,
 7896    window: &mut Window,
 7897    cx: &mut App,
 7898) {
 7899    if source == destination {
 7900        return;
 7901    }
 7902    let Some(active_item) = source.read(cx).active_item() else {
 7903        return;
 7904    };
 7905    source.update(cx, |source_pane, cx| {
 7906        let item_id = active_item.item_id();
 7907        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 7908        destination.update(cx, |target_pane, cx| {
 7909            target_pane.add_item(
 7910                active_item,
 7911                focus_destination,
 7912                focus_destination,
 7913                Some(target_pane.items_len()),
 7914                window,
 7915                cx,
 7916            );
 7917        });
 7918    });
 7919}
 7920
 7921pub fn clone_active_item(
 7922    workspace_id: Option<WorkspaceId>,
 7923    source: &Entity<Pane>,
 7924    destination: &Entity<Pane>,
 7925    focus_destination: bool,
 7926    window: &mut Window,
 7927    cx: &mut App,
 7928) {
 7929    if source == destination {
 7930        return;
 7931    }
 7932    let Some(active_item) = source.read(cx).active_item() else {
 7933        return;
 7934    };
 7935    destination.update(cx, |target_pane, cx| {
 7936        let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
 7937            return;
 7938        };
 7939        target_pane.add_item(
 7940            clone,
 7941            focus_destination,
 7942            focus_destination,
 7943            Some(target_pane.items_len()),
 7944            window,
 7945            cx,
 7946        );
 7947    });
 7948}
 7949
 7950#[derive(Debug)]
 7951pub struct WorkspacePosition {
 7952    pub window_bounds: Option<WindowBounds>,
 7953    pub display: Option<Uuid>,
 7954    pub centered_layout: bool,
 7955}
 7956
 7957pub fn ssh_workspace_position_from_db(
 7958    host: String,
 7959    port: Option<u16>,
 7960    user: Option<String>,
 7961    paths_to_open: &[PathBuf],
 7962    cx: &App,
 7963) -> Task<Result<WorkspacePosition>> {
 7964    let paths = paths_to_open
 7965        .iter()
 7966        .map(|path| path.to_string_lossy().to_string())
 7967        .collect::<Vec<_>>();
 7968
 7969    cx.background_spawn(async move {
 7970        let serialized_ssh_project = persistence::DB
 7971            .get_or_create_ssh_project(host, port, paths, user)
 7972            .await
 7973            .context("fetching serialized ssh project")?;
 7974        let serialized_workspace =
 7975            persistence::DB.workspace_for_ssh_project(&serialized_ssh_project);
 7976
 7977        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 7978            (Some(WindowBounds::Windowed(bounds)), None)
 7979        } else {
 7980            let restorable_bounds = serialized_workspace
 7981                .as_ref()
 7982                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 7983                .or_else(|| {
 7984                    let (display, window_bounds) = DB.last_window().log_err()?;
 7985                    Some((display?, window_bounds?))
 7986                });
 7987
 7988            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 7989                (Some(serialized_status.0), Some(serialized_display))
 7990            } else {
 7991                (None, None)
 7992            }
 7993        };
 7994
 7995        let centered_layout = serialized_workspace
 7996            .as_ref()
 7997            .map(|w| w.centered_layout)
 7998            .unwrap_or(false);
 7999
 8000        Ok(WorkspacePosition {
 8001            window_bounds,
 8002            display,
 8003            centered_layout,
 8004        })
 8005    })
 8006}
 8007
 8008pub fn with_active_or_new_workspace(
 8009    cx: &mut App,
 8010    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8011) {
 8012    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8013        Some(workspace) => {
 8014            cx.defer(move |cx| {
 8015                workspace
 8016                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8017                    .log_err();
 8018            });
 8019        }
 8020        None => {
 8021            let app_state = AppState::global(cx);
 8022            if let Some(app_state) = app_state.upgrade() {
 8023                open_new(
 8024                    OpenOptions::default(),
 8025                    app_state,
 8026                    cx,
 8027                    move |workspace, window, cx| f(workspace, window, cx),
 8028                )
 8029                .detach_and_log_err(cx);
 8030            }
 8031        }
 8032    }
 8033}
 8034
 8035#[cfg(test)]
 8036mod tests {
 8037    use std::{cell::RefCell, rc::Rc};
 8038
 8039    use super::*;
 8040    use crate::{
 8041        dock::{PanelEvent, test::TestPanel},
 8042        item::{
 8043            ItemEvent,
 8044            test::{TestItem, TestProjectItem},
 8045        },
 8046    };
 8047    use fs::FakeFs;
 8048    use gpui::{
 8049        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8050        UpdateGlobal, VisualTestContext, px,
 8051    };
 8052    use project::{Project, ProjectEntryId};
 8053    use serde_json::json;
 8054    use settings::SettingsStore;
 8055
 8056    #[gpui::test]
 8057    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8058        init_test(cx);
 8059
 8060        let fs = FakeFs::new(cx.executor());
 8061        let project = Project::test(fs, [], cx).await;
 8062        let (workspace, cx) =
 8063            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8064
 8065        // Adding an item with no ambiguity renders the tab without detail.
 8066        let item1 = cx.new(|cx| {
 8067            let mut item = TestItem::new(cx);
 8068            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8069            item
 8070        });
 8071        workspace.update_in(cx, |workspace, window, cx| {
 8072            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8073        });
 8074        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8075
 8076        // Adding an item that creates ambiguity increases the level of detail on
 8077        // both tabs.
 8078        let item2 = cx.new_window_entity(|_window, cx| {
 8079            let mut item = TestItem::new(cx);
 8080            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8081            item
 8082        });
 8083        workspace.update_in(cx, |workspace, window, cx| {
 8084            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8085        });
 8086        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8087        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8088
 8089        // Adding an item that creates ambiguity increases the level of detail only
 8090        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8091        // we stop at the highest detail available.
 8092        let item3 = cx.new(|cx| {
 8093            let mut item = TestItem::new(cx);
 8094            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8095            item
 8096        });
 8097        workspace.update_in(cx, |workspace, window, cx| {
 8098            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8099        });
 8100        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8101        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8102        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8103    }
 8104
 8105    #[gpui::test]
 8106    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8107        init_test(cx);
 8108
 8109        let fs = FakeFs::new(cx.executor());
 8110        fs.insert_tree(
 8111            "/root1",
 8112            json!({
 8113                "one.txt": "",
 8114                "two.txt": "",
 8115            }),
 8116        )
 8117        .await;
 8118        fs.insert_tree(
 8119            "/root2",
 8120            json!({
 8121                "three.txt": "",
 8122            }),
 8123        )
 8124        .await;
 8125
 8126        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8127        let (workspace, cx) =
 8128            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8129        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8130        let worktree_id = project.update(cx, |project, cx| {
 8131            project.worktrees(cx).next().unwrap().read(cx).id()
 8132        });
 8133
 8134        let item1 = cx.new(|cx| {
 8135            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8136        });
 8137        let item2 = cx.new(|cx| {
 8138            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8139        });
 8140
 8141        // Add an item to an empty pane
 8142        workspace.update_in(cx, |workspace, window, cx| {
 8143            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8144        });
 8145        project.update(cx, |project, cx| {
 8146            assert_eq!(
 8147                project.active_entry(),
 8148                project
 8149                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8150                    .map(|e| e.id)
 8151            );
 8152        });
 8153        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8154
 8155        // Add a second item to a non-empty pane
 8156        workspace.update_in(cx, |workspace, window, cx| {
 8157            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8158        });
 8159        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8160        project.update(cx, |project, cx| {
 8161            assert_eq!(
 8162                project.active_entry(),
 8163                project
 8164                    .entry_for_path(&(worktree_id, "two.txt").into(), cx)
 8165                    .map(|e| e.id)
 8166            );
 8167        });
 8168
 8169        // Close the active item
 8170        pane.update_in(cx, |pane, window, cx| {
 8171            pane.close_active_item(&Default::default(), window, cx)
 8172        })
 8173        .await
 8174        .unwrap();
 8175        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8176        project.update(cx, |project, cx| {
 8177            assert_eq!(
 8178                project.active_entry(),
 8179                project
 8180                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8181                    .map(|e| e.id)
 8182            );
 8183        });
 8184
 8185        // Add a project folder
 8186        project
 8187            .update(cx, |project, cx| {
 8188                project.find_or_create_worktree("root2", true, cx)
 8189            })
 8190            .await
 8191            .unwrap();
 8192        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8193
 8194        // Remove a project folder
 8195        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8196        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8197    }
 8198
 8199    #[gpui::test]
 8200    async fn test_close_window(cx: &mut TestAppContext) {
 8201        init_test(cx);
 8202
 8203        let fs = FakeFs::new(cx.executor());
 8204        fs.insert_tree("/root", json!({ "one": "" })).await;
 8205
 8206        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8207        let (workspace, cx) =
 8208            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8209
 8210        // When there are no dirty items, there's nothing to do.
 8211        let item1 = cx.new(TestItem::new);
 8212        workspace.update_in(cx, |w, window, cx| {
 8213            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8214        });
 8215        let task = workspace.update_in(cx, |w, window, cx| {
 8216            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8217        });
 8218        assert!(task.await.unwrap());
 8219
 8220        // When there are dirty untitled items, prompt to save each one. If the user
 8221        // cancels any prompt, then abort.
 8222        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8223        let item3 = cx.new(|cx| {
 8224            TestItem::new(cx)
 8225                .with_dirty(true)
 8226                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8227        });
 8228        workspace.update_in(cx, |w, window, cx| {
 8229            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8230            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8231        });
 8232        let task = workspace.update_in(cx, |w, window, cx| {
 8233            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8234        });
 8235        cx.executor().run_until_parked();
 8236        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8237        cx.executor().run_until_parked();
 8238        assert!(!cx.has_pending_prompt());
 8239        assert!(!task.await.unwrap());
 8240    }
 8241
 8242    #[gpui::test]
 8243    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8244        init_test(cx);
 8245
 8246        // Register TestItem as a serializable item
 8247        cx.update(|cx| {
 8248            register_serializable_item::<TestItem>(cx);
 8249        });
 8250
 8251        let fs = FakeFs::new(cx.executor());
 8252        fs.insert_tree("/root", json!({ "one": "" })).await;
 8253
 8254        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8255        let (workspace, cx) =
 8256            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8257
 8258        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8259        let item1 = cx.new(|cx| {
 8260            TestItem::new(cx)
 8261                .with_dirty(true)
 8262                .with_serialize(|| Some(Task::ready(Ok(()))))
 8263        });
 8264        let item2 = cx.new(|cx| {
 8265            TestItem::new(cx)
 8266                .with_dirty(true)
 8267                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8268                .with_serialize(|| Some(Task::ready(Ok(()))))
 8269        });
 8270        workspace.update_in(cx, |w, window, cx| {
 8271            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8272            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8273        });
 8274        let task = workspace.update_in(cx, |w, window, cx| {
 8275            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8276        });
 8277        assert!(task.await.unwrap());
 8278    }
 8279
 8280    #[gpui::test]
 8281    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8282        init_test(cx);
 8283
 8284        let fs = FakeFs::new(cx.executor());
 8285
 8286        let project = Project::test(fs, None, cx).await;
 8287        let (workspace, cx) =
 8288            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8289
 8290        let item1 = cx.new(|cx| {
 8291            TestItem::new(cx)
 8292                .with_dirty(true)
 8293                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8294        });
 8295        let item2 = cx.new(|cx| {
 8296            TestItem::new(cx)
 8297                .with_dirty(true)
 8298                .with_conflict(true)
 8299                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8300        });
 8301        let item3 = cx.new(|cx| {
 8302            TestItem::new(cx)
 8303                .with_dirty(true)
 8304                .with_conflict(true)
 8305                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8306        });
 8307        let item4 = cx.new(|cx| {
 8308            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8309                let project_item = TestProjectItem::new_untitled(cx);
 8310                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8311                project_item
 8312            }])
 8313        });
 8314        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8315            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8316            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8317            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8318            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8319            workspace.active_pane().clone()
 8320        });
 8321
 8322        let close_items = pane.update_in(cx, |pane, window, cx| {
 8323            pane.activate_item(1, true, true, window, cx);
 8324            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8325            let item1_id = item1.item_id();
 8326            let item3_id = item3.item_id();
 8327            let item4_id = item4.item_id();
 8328            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8329                [item1_id, item3_id, item4_id].contains(&id)
 8330            })
 8331        });
 8332        cx.executor().run_until_parked();
 8333
 8334        assert!(cx.has_pending_prompt());
 8335        cx.simulate_prompt_answer("Save all");
 8336
 8337        cx.executor().run_until_parked();
 8338
 8339        // Item 1 is saved. There's a prompt to save item 3.
 8340        pane.update(cx, |pane, cx| {
 8341            assert_eq!(item1.read(cx).save_count, 1);
 8342            assert_eq!(item1.read(cx).save_as_count, 0);
 8343            assert_eq!(item1.read(cx).reload_count, 0);
 8344            assert_eq!(pane.items_len(), 3);
 8345            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8346        });
 8347        assert!(cx.has_pending_prompt());
 8348
 8349        // Cancel saving item 3.
 8350        cx.simulate_prompt_answer("Discard");
 8351        cx.executor().run_until_parked();
 8352
 8353        // Item 3 is reloaded. There's a prompt to save item 4.
 8354        pane.update(cx, |pane, cx| {
 8355            assert_eq!(item3.read(cx).save_count, 0);
 8356            assert_eq!(item3.read(cx).save_as_count, 0);
 8357            assert_eq!(item3.read(cx).reload_count, 1);
 8358            assert_eq!(pane.items_len(), 2);
 8359            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8360        });
 8361
 8362        // There's a prompt for a path for item 4.
 8363        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8364        close_items.await.unwrap();
 8365
 8366        // The requested items are closed.
 8367        pane.update(cx, |pane, cx| {
 8368            assert_eq!(item4.read(cx).save_count, 0);
 8369            assert_eq!(item4.read(cx).save_as_count, 1);
 8370            assert_eq!(item4.read(cx).reload_count, 0);
 8371            assert_eq!(pane.items_len(), 1);
 8372            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8373        });
 8374    }
 8375
 8376    #[gpui::test]
 8377    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8378        init_test(cx);
 8379
 8380        let fs = FakeFs::new(cx.executor());
 8381        let project = Project::test(fs, [], cx).await;
 8382        let (workspace, cx) =
 8383            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8384
 8385        // Create several workspace items with single project entries, and two
 8386        // workspace items with multiple project entries.
 8387        let single_entry_items = (0..=4)
 8388            .map(|project_entry_id| {
 8389                cx.new(|cx| {
 8390                    TestItem::new(cx)
 8391                        .with_dirty(true)
 8392                        .with_project_items(&[dirty_project_item(
 8393                            project_entry_id,
 8394                            &format!("{project_entry_id}.txt"),
 8395                            cx,
 8396                        )])
 8397                })
 8398            })
 8399            .collect::<Vec<_>>();
 8400        let item_2_3 = cx.new(|cx| {
 8401            TestItem::new(cx)
 8402                .with_dirty(true)
 8403                .with_singleton(false)
 8404                .with_project_items(&[
 8405                    single_entry_items[2].read(cx).project_items[0].clone(),
 8406                    single_entry_items[3].read(cx).project_items[0].clone(),
 8407                ])
 8408        });
 8409        let item_3_4 = cx.new(|cx| {
 8410            TestItem::new(cx)
 8411                .with_dirty(true)
 8412                .with_singleton(false)
 8413                .with_project_items(&[
 8414                    single_entry_items[3].read(cx).project_items[0].clone(),
 8415                    single_entry_items[4].read(cx).project_items[0].clone(),
 8416                ])
 8417        });
 8418
 8419        // Create two panes that contain the following project entries:
 8420        //   left pane:
 8421        //     multi-entry items:   (2, 3)
 8422        //     single-entry items:  0, 2, 3, 4
 8423        //   right pane:
 8424        //     single-entry items:  4, 1
 8425        //     multi-entry items:   (3, 4)
 8426        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8427            let left_pane = workspace.active_pane().clone();
 8428            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8429            workspace.add_item_to_active_pane(
 8430                single_entry_items[0].boxed_clone(),
 8431                None,
 8432                true,
 8433                window,
 8434                cx,
 8435            );
 8436            workspace.add_item_to_active_pane(
 8437                single_entry_items[2].boxed_clone(),
 8438                None,
 8439                true,
 8440                window,
 8441                cx,
 8442            );
 8443            workspace.add_item_to_active_pane(
 8444                single_entry_items[3].boxed_clone(),
 8445                None,
 8446                true,
 8447                window,
 8448                cx,
 8449            );
 8450            workspace.add_item_to_active_pane(
 8451                single_entry_items[4].boxed_clone(),
 8452                None,
 8453                true,
 8454                window,
 8455                cx,
 8456            );
 8457
 8458            let right_pane = workspace
 8459                .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
 8460                .unwrap();
 8461
 8462            right_pane.update(cx, |pane, cx| {
 8463                pane.add_item(
 8464                    single_entry_items[1].boxed_clone(),
 8465                    true,
 8466                    true,
 8467                    None,
 8468                    window,
 8469                    cx,
 8470                );
 8471                pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8472            });
 8473
 8474            (left_pane, right_pane)
 8475        });
 8476
 8477        cx.focus(&right_pane);
 8478
 8479        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8480            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8481                .unwrap()
 8482        });
 8483        cx.executor().run_until_parked();
 8484
 8485        let msg = cx.pending_prompt().unwrap().0;
 8486        assert!(msg.contains("1.txt"));
 8487        assert!(!msg.contains("2.txt"));
 8488        assert!(!msg.contains("3.txt"));
 8489        assert!(!msg.contains("4.txt"));
 8490
 8491        cx.simulate_prompt_answer("Cancel");
 8492        close.await;
 8493
 8494        left_pane
 8495            .update_in(cx, |left_pane, window, cx| {
 8496                left_pane.close_item_by_id(
 8497                    single_entry_items[3].entity_id(),
 8498                    SaveIntent::Skip,
 8499                    window,
 8500                    cx,
 8501                )
 8502            })
 8503            .await
 8504            .unwrap();
 8505
 8506        close = right_pane.update_in(cx, |pane, window, cx| {
 8507            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8508                .unwrap()
 8509        });
 8510        cx.executor().run_until_parked();
 8511
 8512        let details = cx.pending_prompt().unwrap().1;
 8513        assert!(details.contains("1.txt"));
 8514        assert!(!details.contains("2.txt"));
 8515        assert!(details.contains("3.txt"));
 8516        // ideally this assertion could be made, but today we can only
 8517        // save whole items not project items, so the orphaned item 3 causes
 8518        // 4 to be saved too.
 8519        // assert!(!details.contains("4.txt"));
 8520
 8521        cx.simulate_prompt_answer("Save all");
 8522
 8523        cx.executor().run_until_parked();
 8524        close.await;
 8525        right_pane.read_with(cx, |pane, _| {
 8526            assert_eq!(pane.items_len(), 0);
 8527        });
 8528    }
 8529
 8530    #[gpui::test]
 8531    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8532        init_test(cx);
 8533
 8534        let fs = FakeFs::new(cx.executor());
 8535        let project = Project::test(fs, [], cx).await;
 8536        let (workspace, cx) =
 8537            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8538        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8539
 8540        let item = cx.new(|cx| {
 8541            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8542        });
 8543        let item_id = item.entity_id();
 8544        workspace.update_in(cx, |workspace, window, cx| {
 8545            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8546        });
 8547
 8548        // Autosave on window change.
 8549        item.update(cx, |item, cx| {
 8550            SettingsStore::update_global(cx, |settings, cx| {
 8551                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8552                    settings.autosave = Some(AutosaveSetting::OnWindowChange);
 8553                })
 8554            });
 8555            item.is_dirty = true;
 8556        });
 8557
 8558        // Deactivating the window saves the file.
 8559        cx.deactivate_window();
 8560        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8561
 8562        // Re-activating the window doesn't save the file.
 8563        cx.update(|window, _| window.activate_window());
 8564        cx.executor().run_until_parked();
 8565        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8566
 8567        // Autosave on focus change.
 8568        item.update_in(cx, |item, window, cx| {
 8569            cx.focus_self(window);
 8570            SettingsStore::update_global(cx, |settings, cx| {
 8571                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8572                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8573                })
 8574            });
 8575            item.is_dirty = true;
 8576        });
 8577
 8578        // Blurring the item saves the file.
 8579        item.update_in(cx, |_, window, _| window.blur());
 8580        cx.executor().run_until_parked();
 8581        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8582
 8583        // Deactivating the window still saves the file.
 8584        item.update_in(cx, |item, window, cx| {
 8585            cx.focus_self(window);
 8586            item.is_dirty = true;
 8587        });
 8588        cx.deactivate_window();
 8589        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8590
 8591        // Autosave after delay.
 8592        item.update(cx, |item, cx| {
 8593            SettingsStore::update_global(cx, |settings, cx| {
 8594                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8595                    settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
 8596                })
 8597            });
 8598            item.is_dirty = true;
 8599            cx.emit(ItemEvent::Edit);
 8600        });
 8601
 8602        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8603        cx.executor().advance_clock(Duration::from_millis(250));
 8604        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8605
 8606        // After delay expires, the file is saved.
 8607        cx.executor().advance_clock(Duration::from_millis(250));
 8608        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8609
 8610        // Autosave on focus change, ensuring closing the tab counts as such.
 8611        item.update(cx, |item, cx| {
 8612            SettingsStore::update_global(cx, |settings, cx| {
 8613                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8614                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8615                })
 8616            });
 8617            item.is_dirty = true;
 8618            for project_item in &mut item.project_items {
 8619                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8620            }
 8621        });
 8622
 8623        pane.update_in(cx, |pane, window, cx| {
 8624            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8625        })
 8626        .await
 8627        .unwrap();
 8628        assert!(!cx.has_pending_prompt());
 8629        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8630
 8631        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8632        workspace.update_in(cx, |workspace, window, cx| {
 8633            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8634        });
 8635        item.update_in(cx, |item, window, cx| {
 8636            item.project_items[0].update(cx, |item, _| {
 8637                item.entry_id = None;
 8638            });
 8639            item.is_dirty = true;
 8640            window.blur();
 8641        });
 8642        cx.run_until_parked();
 8643        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8644
 8645        // Ensure autosave is prevented for deleted files also when closing the buffer.
 8646        let _close_items = pane.update_in(cx, |pane, window, cx| {
 8647            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8648        });
 8649        cx.run_until_parked();
 8650        assert!(cx.has_pending_prompt());
 8651        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8652    }
 8653
 8654    #[gpui::test]
 8655    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 8656        init_test(cx);
 8657
 8658        let fs = FakeFs::new(cx.executor());
 8659
 8660        let project = Project::test(fs, [], cx).await;
 8661        let (workspace, cx) =
 8662            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8663
 8664        let item = cx.new(|cx| {
 8665            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8666        });
 8667        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8668        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 8669        let toolbar_notify_count = Rc::new(RefCell::new(0));
 8670
 8671        workspace.update_in(cx, |workspace, window, cx| {
 8672            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8673            let toolbar_notification_count = toolbar_notify_count.clone();
 8674            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 8675                *toolbar_notification_count.borrow_mut() += 1
 8676            })
 8677            .detach();
 8678        });
 8679
 8680        pane.read_with(cx, |pane, _| {
 8681            assert!(!pane.can_navigate_backward());
 8682            assert!(!pane.can_navigate_forward());
 8683        });
 8684
 8685        item.update_in(cx, |item, _, cx| {
 8686            item.set_state("one".to_string(), cx);
 8687        });
 8688
 8689        // Toolbar must be notified to re-render the navigation buttons
 8690        assert_eq!(*toolbar_notify_count.borrow(), 1);
 8691
 8692        pane.read_with(cx, |pane, _| {
 8693            assert!(pane.can_navigate_backward());
 8694            assert!(!pane.can_navigate_forward());
 8695        });
 8696
 8697        workspace
 8698            .update_in(cx, |workspace, window, cx| {
 8699                workspace.go_back(pane.downgrade(), window, cx)
 8700            })
 8701            .await
 8702            .unwrap();
 8703
 8704        assert_eq!(*toolbar_notify_count.borrow(), 2);
 8705        pane.read_with(cx, |pane, _| {
 8706            assert!(!pane.can_navigate_backward());
 8707            assert!(pane.can_navigate_forward());
 8708        });
 8709    }
 8710
 8711    #[gpui::test]
 8712    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 8713        init_test(cx);
 8714        let fs = FakeFs::new(cx.executor());
 8715
 8716        let project = Project::test(fs, [], cx).await;
 8717        let (workspace, cx) =
 8718            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8719
 8720        let panel = workspace.update_in(cx, |workspace, window, cx| {
 8721            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 8722            workspace.add_panel(panel.clone(), window, cx);
 8723
 8724            workspace
 8725                .right_dock()
 8726                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 8727
 8728            panel
 8729        });
 8730
 8731        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8732        pane.update_in(cx, |pane, window, cx| {
 8733            let item = cx.new(TestItem::new);
 8734            pane.add_item(Box::new(item), true, true, None, window, cx);
 8735        });
 8736
 8737        // Transfer focus from center to panel
 8738        workspace.update_in(cx, |workspace, window, cx| {
 8739            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8740        });
 8741
 8742        workspace.update_in(cx, |workspace, window, cx| {
 8743            assert!(workspace.right_dock().read(cx).is_open());
 8744            assert!(!panel.is_zoomed(window, cx));
 8745            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8746        });
 8747
 8748        // Transfer focus from panel to center
 8749        workspace.update_in(cx, |workspace, window, cx| {
 8750            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8751        });
 8752
 8753        workspace.update_in(cx, |workspace, window, cx| {
 8754            assert!(workspace.right_dock().read(cx).is_open());
 8755            assert!(!panel.is_zoomed(window, cx));
 8756            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8757        });
 8758
 8759        // Close the dock
 8760        workspace.update_in(cx, |workspace, window, cx| {
 8761            workspace.toggle_dock(DockPosition::Right, window, cx);
 8762        });
 8763
 8764        workspace.update_in(cx, |workspace, window, cx| {
 8765            assert!(!workspace.right_dock().read(cx).is_open());
 8766            assert!(!panel.is_zoomed(window, cx));
 8767            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8768        });
 8769
 8770        // Open the dock
 8771        workspace.update_in(cx, |workspace, window, cx| {
 8772            workspace.toggle_dock(DockPosition::Right, window, cx);
 8773        });
 8774
 8775        workspace.update_in(cx, |workspace, window, cx| {
 8776            assert!(workspace.right_dock().read(cx).is_open());
 8777            assert!(!panel.is_zoomed(window, cx));
 8778            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8779        });
 8780
 8781        // Focus and zoom panel
 8782        panel.update_in(cx, |panel, window, cx| {
 8783            cx.focus_self(window);
 8784            panel.set_zoomed(true, window, cx)
 8785        });
 8786
 8787        workspace.update_in(cx, |workspace, window, cx| {
 8788            assert!(workspace.right_dock().read(cx).is_open());
 8789            assert!(panel.is_zoomed(window, cx));
 8790            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8791        });
 8792
 8793        // Transfer focus to the center closes the dock
 8794        workspace.update_in(cx, |workspace, window, cx| {
 8795            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8796        });
 8797
 8798        workspace.update_in(cx, |workspace, window, cx| {
 8799            assert!(!workspace.right_dock().read(cx).is_open());
 8800            assert!(panel.is_zoomed(window, cx));
 8801            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8802        });
 8803
 8804        // Transferring focus back to the panel keeps it zoomed
 8805        workspace.update_in(cx, |workspace, window, cx| {
 8806            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8807        });
 8808
 8809        workspace.update_in(cx, |workspace, window, cx| {
 8810            assert!(workspace.right_dock().read(cx).is_open());
 8811            assert!(panel.is_zoomed(window, cx));
 8812            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8813        });
 8814
 8815        // Close the dock while it is zoomed
 8816        workspace.update_in(cx, |workspace, window, cx| {
 8817            workspace.toggle_dock(DockPosition::Right, window, cx)
 8818        });
 8819
 8820        workspace.update_in(cx, |workspace, window, cx| {
 8821            assert!(!workspace.right_dock().read(cx).is_open());
 8822            assert!(panel.is_zoomed(window, cx));
 8823            assert!(workspace.zoomed.is_none());
 8824            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8825        });
 8826
 8827        // Opening the dock, when it's zoomed, retains focus
 8828        workspace.update_in(cx, |workspace, window, cx| {
 8829            workspace.toggle_dock(DockPosition::Right, window, cx)
 8830        });
 8831
 8832        workspace.update_in(cx, |workspace, window, cx| {
 8833            assert!(workspace.right_dock().read(cx).is_open());
 8834            assert!(panel.is_zoomed(window, cx));
 8835            assert!(workspace.zoomed.is_some());
 8836            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8837        });
 8838
 8839        // Unzoom and close the panel, zoom the active pane.
 8840        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 8841        workspace.update_in(cx, |workspace, window, cx| {
 8842            workspace.toggle_dock(DockPosition::Right, window, cx)
 8843        });
 8844        pane.update_in(cx, |pane, window, cx| {
 8845            pane.toggle_zoom(&Default::default(), window, cx)
 8846        });
 8847
 8848        // Opening a dock unzooms the pane.
 8849        workspace.update_in(cx, |workspace, window, cx| {
 8850            workspace.toggle_dock(DockPosition::Right, window, cx)
 8851        });
 8852        workspace.update_in(cx, |workspace, window, cx| {
 8853            let pane = pane.read(cx);
 8854            assert!(!pane.is_zoomed());
 8855            assert!(!pane.focus_handle(cx).is_focused(window));
 8856            assert!(workspace.right_dock().read(cx).is_open());
 8857            assert!(workspace.zoomed.is_none());
 8858        });
 8859    }
 8860
 8861    #[gpui::test]
 8862    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 8863        init_test(cx);
 8864
 8865        let fs = FakeFs::new(cx.executor());
 8866
 8867        let project = Project::test(fs, None, cx).await;
 8868        let (workspace, cx) =
 8869            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8870
 8871        // Let's arrange the panes like this:
 8872        //
 8873        // +-----------------------+
 8874        // |         top           |
 8875        // +------+--------+-------+
 8876        // | left | center | right |
 8877        // +------+--------+-------+
 8878        // |        bottom         |
 8879        // +-----------------------+
 8880
 8881        let top_item = cx.new(|cx| {
 8882            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 8883        });
 8884        let bottom_item = cx.new(|cx| {
 8885            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 8886        });
 8887        let left_item = cx.new(|cx| {
 8888            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 8889        });
 8890        let right_item = cx.new(|cx| {
 8891            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 8892        });
 8893        let center_item = cx.new(|cx| {
 8894            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 8895        });
 8896
 8897        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8898            let top_pane_id = workspace.active_pane().entity_id();
 8899            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 8900            workspace.split_pane(
 8901                workspace.active_pane().clone(),
 8902                SplitDirection::Down,
 8903                window,
 8904                cx,
 8905            );
 8906            top_pane_id
 8907        });
 8908        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8909            let bottom_pane_id = workspace.active_pane().entity_id();
 8910            workspace.add_item_to_active_pane(
 8911                Box::new(bottom_item.clone()),
 8912                None,
 8913                false,
 8914                window,
 8915                cx,
 8916            );
 8917            workspace.split_pane(
 8918                workspace.active_pane().clone(),
 8919                SplitDirection::Up,
 8920                window,
 8921                cx,
 8922            );
 8923            bottom_pane_id
 8924        });
 8925        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8926            let left_pane_id = workspace.active_pane().entity_id();
 8927            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 8928            workspace.split_pane(
 8929                workspace.active_pane().clone(),
 8930                SplitDirection::Right,
 8931                window,
 8932                cx,
 8933            );
 8934            left_pane_id
 8935        });
 8936        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8937            let right_pane_id = workspace.active_pane().entity_id();
 8938            workspace.add_item_to_active_pane(
 8939                Box::new(right_item.clone()),
 8940                None,
 8941                false,
 8942                window,
 8943                cx,
 8944            );
 8945            workspace.split_pane(
 8946                workspace.active_pane().clone(),
 8947                SplitDirection::Left,
 8948                window,
 8949                cx,
 8950            );
 8951            right_pane_id
 8952        });
 8953        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8954            let center_pane_id = workspace.active_pane().entity_id();
 8955            workspace.add_item_to_active_pane(
 8956                Box::new(center_item.clone()),
 8957                None,
 8958                false,
 8959                window,
 8960                cx,
 8961            );
 8962            center_pane_id
 8963        });
 8964        cx.executor().run_until_parked();
 8965
 8966        workspace.update_in(cx, |workspace, window, cx| {
 8967            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 8968
 8969            // Join into next from center pane into right
 8970            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 8971        });
 8972
 8973        workspace.update_in(cx, |workspace, window, cx| {
 8974            let active_pane = workspace.active_pane();
 8975            assert_eq!(right_pane_id, active_pane.entity_id());
 8976            assert_eq!(2, active_pane.read(cx).items_len());
 8977            let item_ids_in_pane =
 8978                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 8979            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 8980            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 8981
 8982            // Join into next from right pane into bottom
 8983            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 8984        });
 8985
 8986        workspace.update_in(cx, |workspace, window, cx| {
 8987            let active_pane = workspace.active_pane();
 8988            assert_eq!(bottom_pane_id, active_pane.entity_id());
 8989            assert_eq!(3, active_pane.read(cx).items_len());
 8990            let item_ids_in_pane =
 8991                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 8992            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 8993            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 8994            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 8995
 8996            // Join into next from bottom pane into left
 8997            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 8998        });
 8999
 9000        workspace.update_in(cx, |workspace, window, cx| {
 9001            let active_pane = workspace.active_pane();
 9002            assert_eq!(left_pane_id, active_pane.entity_id());
 9003            assert_eq!(4, active_pane.read(cx).items_len());
 9004            let item_ids_in_pane =
 9005                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9006            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9007            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9008            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9009            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9010
 9011            // Join into next from left pane into top
 9012            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9013        });
 9014
 9015        workspace.update_in(cx, |workspace, window, cx| {
 9016            let active_pane = workspace.active_pane();
 9017            assert_eq!(top_pane_id, active_pane.entity_id());
 9018            assert_eq!(5, active_pane.read(cx).items_len());
 9019            let item_ids_in_pane =
 9020                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9021            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9022            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9023            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9024            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9025            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9026
 9027            // Single pane left: no-op
 9028            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9029        });
 9030
 9031        workspace.update(cx, |workspace, _cx| {
 9032            let active_pane = workspace.active_pane();
 9033            assert_eq!(top_pane_id, active_pane.entity_id());
 9034        });
 9035    }
 9036
 9037    fn add_an_item_to_active_pane(
 9038        cx: &mut VisualTestContext,
 9039        workspace: &Entity<Workspace>,
 9040        item_id: u64,
 9041    ) -> Entity<TestItem> {
 9042        let item = cx.new(|cx| {
 9043            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9044                item_id,
 9045                "item{item_id}.txt",
 9046                cx,
 9047            )])
 9048        });
 9049        workspace.update_in(cx, |workspace, window, cx| {
 9050            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9051        });
 9052        return item;
 9053    }
 9054
 9055    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9056        return workspace.update_in(cx, |workspace, window, cx| {
 9057            let new_pane = workspace.split_pane(
 9058                workspace.active_pane().clone(),
 9059                SplitDirection::Right,
 9060                window,
 9061                cx,
 9062            );
 9063            new_pane
 9064        });
 9065    }
 9066
 9067    #[gpui::test]
 9068    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9069        init_test(cx);
 9070        let fs = FakeFs::new(cx.executor());
 9071        let project = Project::test(fs, None, cx).await;
 9072        let (workspace, cx) =
 9073            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9074
 9075        add_an_item_to_active_pane(cx, &workspace, 1);
 9076        split_pane(cx, &workspace);
 9077        add_an_item_to_active_pane(cx, &workspace, 2);
 9078        split_pane(cx, &workspace); // empty pane
 9079        split_pane(cx, &workspace);
 9080        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9081
 9082        cx.executor().run_until_parked();
 9083
 9084        workspace.update(cx, |workspace, cx| {
 9085            let num_panes = workspace.panes().len();
 9086            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9087            let active_item = workspace
 9088                .active_pane()
 9089                .read(cx)
 9090                .active_item()
 9091                .expect("item is in focus");
 9092
 9093            assert_eq!(num_panes, 4);
 9094            assert_eq!(num_items_in_current_pane, 1);
 9095            assert_eq!(active_item.item_id(), last_item.item_id());
 9096        });
 9097
 9098        workspace.update_in(cx, |workspace, window, cx| {
 9099            workspace.join_all_panes(window, cx);
 9100        });
 9101
 9102        workspace.update(cx, |workspace, cx| {
 9103            let num_panes = workspace.panes().len();
 9104            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9105            let active_item = workspace
 9106                .active_pane()
 9107                .read(cx)
 9108                .active_item()
 9109                .expect("item is in focus");
 9110
 9111            assert_eq!(num_panes, 1);
 9112            assert_eq!(num_items_in_current_pane, 3);
 9113            assert_eq!(active_item.item_id(), last_item.item_id());
 9114        });
 9115    }
 9116    struct TestModal(FocusHandle);
 9117
 9118    impl TestModal {
 9119        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9120            Self(cx.focus_handle())
 9121        }
 9122    }
 9123
 9124    impl EventEmitter<DismissEvent> for TestModal {}
 9125
 9126    impl Focusable for TestModal {
 9127        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9128            self.0.clone()
 9129        }
 9130    }
 9131
 9132    impl ModalView for TestModal {}
 9133
 9134    impl Render for TestModal {
 9135        fn render(
 9136            &mut self,
 9137            _window: &mut Window,
 9138            _cx: &mut Context<TestModal>,
 9139        ) -> impl IntoElement {
 9140            div().track_focus(&self.0)
 9141        }
 9142    }
 9143
 9144    #[gpui::test]
 9145    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9146        init_test(cx);
 9147        let fs = FakeFs::new(cx.executor());
 9148
 9149        let project = Project::test(fs, [], cx).await;
 9150        let (workspace, cx) =
 9151            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9152
 9153        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9154            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9155            workspace.add_panel(panel_1.clone(), window, cx);
 9156            workspace.toggle_dock(DockPosition::Left, window, cx);
 9157            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9158            workspace.add_panel(panel_2.clone(), window, cx);
 9159            workspace.toggle_dock(DockPosition::Right, window, cx);
 9160
 9161            let left_dock = workspace.left_dock();
 9162            assert_eq!(
 9163                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9164                panel_1.panel_id()
 9165            );
 9166            assert_eq!(
 9167                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9168                panel_1.size(window, cx)
 9169            );
 9170
 9171            left_dock.update(cx, |left_dock, cx| {
 9172                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9173            });
 9174            assert_eq!(
 9175                workspace
 9176                    .right_dock()
 9177                    .read(cx)
 9178                    .visible_panel()
 9179                    .unwrap()
 9180                    .panel_id(),
 9181                panel_2.panel_id(),
 9182            );
 9183
 9184            (panel_1, panel_2)
 9185        });
 9186
 9187        // Move panel_1 to the right
 9188        panel_1.update_in(cx, |panel_1, window, cx| {
 9189            panel_1.set_position(DockPosition::Right, window, cx)
 9190        });
 9191
 9192        workspace.update_in(cx, |workspace, window, cx| {
 9193            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9194            // Since it was the only panel on the left, the left dock should now be closed.
 9195            assert!(!workspace.left_dock().read(cx).is_open());
 9196            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9197            let right_dock = workspace.right_dock();
 9198            assert_eq!(
 9199                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9200                panel_1.panel_id()
 9201            );
 9202            assert_eq!(
 9203                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9204                px(1337.)
 9205            );
 9206
 9207            // Now we move panel_2 to the left
 9208            panel_2.set_position(DockPosition::Left, window, cx);
 9209        });
 9210
 9211        workspace.update(cx, |workspace, cx| {
 9212            // Since panel_2 was not visible on the right, we don't open the left dock.
 9213            assert!(!workspace.left_dock().read(cx).is_open());
 9214            // And the right dock is unaffected in its displaying of panel_1
 9215            assert!(workspace.right_dock().read(cx).is_open());
 9216            assert_eq!(
 9217                workspace
 9218                    .right_dock()
 9219                    .read(cx)
 9220                    .visible_panel()
 9221                    .unwrap()
 9222                    .panel_id(),
 9223                panel_1.panel_id(),
 9224            );
 9225        });
 9226
 9227        // Move panel_1 back to the left
 9228        panel_1.update_in(cx, |panel_1, window, cx| {
 9229            panel_1.set_position(DockPosition::Left, window, cx)
 9230        });
 9231
 9232        workspace.update_in(cx, |workspace, window, cx| {
 9233            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9234            let left_dock = workspace.left_dock();
 9235            assert!(left_dock.read(cx).is_open());
 9236            assert_eq!(
 9237                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9238                panel_1.panel_id()
 9239            );
 9240            assert_eq!(
 9241                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9242                px(1337.)
 9243            );
 9244            // And the right dock should be closed as it no longer has any panels.
 9245            assert!(!workspace.right_dock().read(cx).is_open());
 9246
 9247            // Now we move panel_1 to the bottom
 9248            panel_1.set_position(DockPosition::Bottom, window, cx);
 9249        });
 9250
 9251        workspace.update_in(cx, |workspace, window, cx| {
 9252            // Since panel_1 was visible on the left, we close the left dock.
 9253            assert!(!workspace.left_dock().read(cx).is_open());
 9254            // The bottom dock is sized based on the panel's default size,
 9255            // since the panel orientation changed from vertical to horizontal.
 9256            let bottom_dock = workspace.bottom_dock();
 9257            assert_eq!(
 9258                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9259                panel_1.size(window, cx),
 9260            );
 9261            // Close bottom dock and move panel_1 back to the left.
 9262            bottom_dock.update(cx, |bottom_dock, cx| {
 9263                bottom_dock.set_open(false, window, cx)
 9264            });
 9265            panel_1.set_position(DockPosition::Left, window, cx);
 9266        });
 9267
 9268        // Emit activated event on panel 1
 9269        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9270
 9271        // Now the left dock is open and panel_1 is active and focused.
 9272        workspace.update_in(cx, |workspace, window, cx| {
 9273            let left_dock = workspace.left_dock();
 9274            assert!(left_dock.read(cx).is_open());
 9275            assert_eq!(
 9276                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9277                panel_1.panel_id(),
 9278            );
 9279            assert!(panel_1.focus_handle(cx).is_focused(window));
 9280        });
 9281
 9282        // Emit closed event on panel 2, which is not active
 9283        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9284
 9285        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9286        workspace.update(cx, |workspace, cx| {
 9287            let left_dock = workspace.left_dock();
 9288            assert!(left_dock.read(cx).is_open());
 9289            assert_eq!(
 9290                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9291                panel_1.panel_id(),
 9292            );
 9293        });
 9294
 9295        // Emitting a ZoomIn event shows the panel as zoomed.
 9296        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9297        workspace.read_with(cx, |workspace, _| {
 9298            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9299            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9300        });
 9301
 9302        // Move panel to another dock while it is zoomed
 9303        panel_1.update_in(cx, |panel, window, cx| {
 9304            panel.set_position(DockPosition::Right, window, cx)
 9305        });
 9306        workspace.read_with(cx, |workspace, _| {
 9307            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9308
 9309            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9310        });
 9311
 9312        // This is a helper for getting a:
 9313        // - valid focus on an element,
 9314        // - that isn't a part of the panes and panels system of the Workspace,
 9315        // - and doesn't trigger the 'on_focus_lost' API.
 9316        let focus_other_view = {
 9317            let workspace = workspace.clone();
 9318            move |cx: &mut VisualTestContext| {
 9319                workspace.update_in(cx, |workspace, window, cx| {
 9320                    if let Some(_) = workspace.active_modal::<TestModal>(cx) {
 9321                        workspace.toggle_modal(window, cx, TestModal::new);
 9322                        workspace.toggle_modal(window, cx, TestModal::new);
 9323                    } else {
 9324                        workspace.toggle_modal(window, cx, TestModal::new);
 9325                    }
 9326                })
 9327            }
 9328        };
 9329
 9330        // If focus is transferred to another view that's not a panel or another pane, we still show
 9331        // the panel as zoomed.
 9332        focus_other_view(cx);
 9333        workspace.read_with(cx, |workspace, _| {
 9334            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9335            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9336        });
 9337
 9338        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9339        workspace.update_in(cx, |_workspace, window, cx| {
 9340            cx.focus_self(window);
 9341        });
 9342        workspace.read_with(cx, |workspace, _| {
 9343            assert_eq!(workspace.zoomed, None);
 9344            assert_eq!(workspace.zoomed_position, None);
 9345        });
 9346
 9347        // If focus is transferred again to another view that's not a panel or a pane, we won't
 9348        // show the panel as zoomed because it wasn't zoomed before.
 9349        focus_other_view(cx);
 9350        workspace.read_with(cx, |workspace, _| {
 9351            assert_eq!(workspace.zoomed, None);
 9352            assert_eq!(workspace.zoomed_position, None);
 9353        });
 9354
 9355        // When the panel is activated, it is zoomed again.
 9356        cx.dispatch_action(ToggleRightDock);
 9357        workspace.read_with(cx, |workspace, _| {
 9358            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9359            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9360        });
 9361
 9362        // Emitting a ZoomOut event unzooms the panel.
 9363        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
 9364        workspace.read_with(cx, |workspace, _| {
 9365            assert_eq!(workspace.zoomed, None);
 9366            assert_eq!(workspace.zoomed_position, None);
 9367        });
 9368
 9369        // Emit closed event on panel 1, which is active
 9370        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9371
 9372        // Now the left dock is closed, because panel_1 was the active panel
 9373        workspace.update(cx, |workspace, cx| {
 9374            let right_dock = workspace.right_dock();
 9375            assert!(!right_dock.read(cx).is_open());
 9376        });
 9377    }
 9378
 9379    #[gpui::test]
 9380    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
 9381        init_test(cx);
 9382
 9383        let fs = FakeFs::new(cx.background_executor.clone());
 9384        let project = Project::test(fs, [], cx).await;
 9385        let (workspace, cx) =
 9386            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9387        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9388
 9389        let dirty_regular_buffer = cx.new(|cx| {
 9390            TestItem::new(cx)
 9391                .with_dirty(true)
 9392                .with_label("1.txt")
 9393                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9394        });
 9395        let dirty_regular_buffer_2 = cx.new(|cx| {
 9396            TestItem::new(cx)
 9397                .with_dirty(true)
 9398                .with_label("2.txt")
 9399                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9400        });
 9401        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9402            TestItem::new(cx)
 9403                .with_dirty(true)
 9404                .with_singleton(false)
 9405                .with_label("Fake Project Search")
 9406                .with_project_items(&[
 9407                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9408                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9409                ])
 9410        });
 9411        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9412        workspace.update_in(cx, |workspace, window, cx| {
 9413            workspace.add_item(
 9414                pane.clone(),
 9415                Box::new(dirty_regular_buffer.clone()),
 9416                None,
 9417                false,
 9418                false,
 9419                window,
 9420                cx,
 9421            );
 9422            workspace.add_item(
 9423                pane.clone(),
 9424                Box::new(dirty_regular_buffer_2.clone()),
 9425                None,
 9426                false,
 9427                false,
 9428                window,
 9429                cx,
 9430            );
 9431            workspace.add_item(
 9432                pane.clone(),
 9433                Box::new(dirty_multi_buffer_with_both.clone()),
 9434                None,
 9435                false,
 9436                false,
 9437                window,
 9438                cx,
 9439            );
 9440        });
 9441
 9442        pane.update_in(cx, |pane, window, cx| {
 9443            pane.activate_item(2, true, true, window, cx);
 9444            assert_eq!(
 9445                pane.active_item().unwrap().item_id(),
 9446                multi_buffer_with_both_files_id,
 9447                "Should select the multi buffer in the pane"
 9448            );
 9449        });
 9450        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9451            pane.close_inactive_items(
 9452                &CloseInactiveItems {
 9453                    save_intent: Some(SaveIntent::Save),
 9454                    close_pinned: true,
 9455                },
 9456                None,
 9457                window,
 9458                cx,
 9459            )
 9460        });
 9461        cx.background_executor.run_until_parked();
 9462        assert!(!cx.has_pending_prompt());
 9463        close_all_but_multi_buffer_task
 9464            .await
 9465            .expect("Closing all buffers but the multi buffer failed");
 9466        pane.update(cx, |pane, cx| {
 9467            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9468            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9469            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9470            assert_eq!(pane.items_len(), 1);
 9471            assert_eq!(
 9472                pane.active_item().unwrap().item_id(),
 9473                multi_buffer_with_both_files_id,
 9474                "Should have only the multi buffer left in the pane"
 9475            );
 9476            assert!(
 9477                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9478                "The multi buffer containing the unsaved buffer should still be dirty"
 9479            );
 9480        });
 9481
 9482        dirty_regular_buffer.update(cx, |buffer, cx| {
 9483            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9484        });
 9485
 9486        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9487            pane.close_active_item(
 9488                &CloseActiveItem {
 9489                    save_intent: Some(SaveIntent::Close),
 9490                    close_pinned: false,
 9491                },
 9492                window,
 9493                cx,
 9494            )
 9495        });
 9496        cx.background_executor.run_until_parked();
 9497        assert!(
 9498            cx.has_pending_prompt(),
 9499            "Dirty multi buffer should prompt a save dialog"
 9500        );
 9501        cx.simulate_prompt_answer("Save");
 9502        cx.background_executor.run_until_parked();
 9503        close_multi_buffer_task
 9504            .await
 9505            .expect("Closing the multi buffer failed");
 9506        pane.update(cx, |pane, cx| {
 9507            assert_eq!(
 9508                dirty_multi_buffer_with_both.read(cx).save_count,
 9509                1,
 9510                "Multi buffer item should get be saved"
 9511            );
 9512            // Test impl does not save inner items, so we do not assert them
 9513            assert_eq!(
 9514                pane.items_len(),
 9515                0,
 9516                "No more items should be left in the pane"
 9517            );
 9518            assert!(pane.active_item().is_none());
 9519        });
 9520    }
 9521
 9522    #[gpui::test]
 9523    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9524        cx: &mut TestAppContext,
 9525    ) {
 9526        init_test(cx);
 9527
 9528        let fs = FakeFs::new(cx.background_executor.clone());
 9529        let project = Project::test(fs, [], cx).await;
 9530        let (workspace, cx) =
 9531            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9532        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9533
 9534        let dirty_regular_buffer = cx.new(|cx| {
 9535            TestItem::new(cx)
 9536                .with_dirty(true)
 9537                .with_label("1.txt")
 9538                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9539        });
 9540        let dirty_regular_buffer_2 = cx.new(|cx| {
 9541            TestItem::new(cx)
 9542                .with_dirty(true)
 9543                .with_label("2.txt")
 9544                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9545        });
 9546        let clear_regular_buffer = cx.new(|cx| {
 9547            TestItem::new(cx)
 9548                .with_label("3.txt")
 9549                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9550        });
 9551
 9552        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9553            TestItem::new(cx)
 9554                .with_dirty(true)
 9555                .with_singleton(false)
 9556                .with_label("Fake Project Search")
 9557                .with_project_items(&[
 9558                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9559                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9560                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9561                ])
 9562        });
 9563        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9564        workspace.update_in(cx, |workspace, window, cx| {
 9565            workspace.add_item(
 9566                pane.clone(),
 9567                Box::new(dirty_regular_buffer.clone()),
 9568                None,
 9569                false,
 9570                false,
 9571                window,
 9572                cx,
 9573            );
 9574            workspace.add_item(
 9575                pane.clone(),
 9576                Box::new(dirty_multi_buffer_with_both.clone()),
 9577                None,
 9578                false,
 9579                false,
 9580                window,
 9581                cx,
 9582            );
 9583        });
 9584
 9585        pane.update_in(cx, |pane, window, cx| {
 9586            pane.activate_item(1, true, true, window, cx);
 9587            assert_eq!(
 9588                pane.active_item().unwrap().item_id(),
 9589                multi_buffer_with_both_files_id,
 9590                "Should select the multi buffer in the pane"
 9591            );
 9592        });
 9593        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9594            pane.close_active_item(
 9595                &CloseActiveItem {
 9596                    save_intent: None,
 9597                    close_pinned: false,
 9598                },
 9599                window,
 9600                cx,
 9601            )
 9602        });
 9603        cx.background_executor.run_until_parked();
 9604        assert!(
 9605            cx.has_pending_prompt(),
 9606            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9607        );
 9608    }
 9609
 9610    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9611    /// closed when they are deleted from disk.
 9612    #[gpui::test]
 9613    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9614        init_test(cx);
 9615
 9616        // Enable the close_on_disk_deletion setting
 9617        cx.update_global(|store: &mut SettingsStore, cx| {
 9618            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9619                settings.close_on_file_delete = Some(true);
 9620            });
 9621        });
 9622
 9623        let fs = FakeFs::new(cx.background_executor.clone());
 9624        let project = Project::test(fs, [], cx).await;
 9625        let (workspace, cx) =
 9626            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9627        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9628
 9629        // Create a test item that simulates a file
 9630        let item = cx.new(|cx| {
 9631            TestItem::new(cx)
 9632                .with_label("test.txt")
 9633                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9634        });
 9635
 9636        // Add item to workspace
 9637        workspace.update_in(cx, |workspace, window, cx| {
 9638            workspace.add_item(
 9639                pane.clone(),
 9640                Box::new(item.clone()),
 9641                None,
 9642                false,
 9643                false,
 9644                window,
 9645                cx,
 9646            );
 9647        });
 9648
 9649        // Verify the item is in the pane
 9650        pane.read_with(cx, |pane, _| {
 9651            assert_eq!(pane.items().count(), 1);
 9652        });
 9653
 9654        // Simulate file deletion by setting the item's deleted state
 9655        item.update(cx, |item, _| {
 9656            item.set_has_deleted_file(true);
 9657        });
 9658
 9659        // Emit UpdateTab event to trigger the close behavior
 9660        cx.run_until_parked();
 9661        item.update(cx, |_, cx| {
 9662            cx.emit(ItemEvent::UpdateTab);
 9663        });
 9664
 9665        // Allow the close operation to complete
 9666        cx.run_until_parked();
 9667
 9668        // Verify the item was automatically closed
 9669        pane.read_with(cx, |pane, _| {
 9670            assert_eq!(
 9671                pane.items().count(),
 9672                0,
 9673                "Item should be automatically closed when file is deleted"
 9674            );
 9675        });
 9676    }
 9677
 9678    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9679    /// open with a strikethrough when they are deleted from disk.
 9680    #[gpui::test]
 9681    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9682        init_test(cx);
 9683
 9684        // Ensure close_on_disk_deletion is disabled (default)
 9685        cx.update_global(|store: &mut SettingsStore, cx| {
 9686            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9687                settings.close_on_file_delete = Some(false);
 9688            });
 9689        });
 9690
 9691        let fs = FakeFs::new(cx.background_executor.clone());
 9692        let project = Project::test(fs, [], cx).await;
 9693        let (workspace, cx) =
 9694            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9695        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9696
 9697        // Create a test item that simulates a file
 9698        let item = cx.new(|cx| {
 9699            TestItem::new(cx)
 9700                .with_label("test.txt")
 9701                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9702        });
 9703
 9704        // Add item to workspace
 9705        workspace.update_in(cx, |workspace, window, cx| {
 9706            workspace.add_item(
 9707                pane.clone(),
 9708                Box::new(item.clone()),
 9709                None,
 9710                false,
 9711                false,
 9712                window,
 9713                cx,
 9714            );
 9715        });
 9716
 9717        // Verify the item is in the pane
 9718        pane.read_with(cx, |pane, _| {
 9719            assert_eq!(pane.items().count(), 1);
 9720        });
 9721
 9722        // Simulate file deletion
 9723        item.update(cx, |item, _| {
 9724            item.set_has_deleted_file(true);
 9725        });
 9726
 9727        // Emit UpdateTab event
 9728        cx.run_until_parked();
 9729        item.update(cx, |_, cx| {
 9730            cx.emit(ItemEvent::UpdateTab);
 9731        });
 9732
 9733        // Allow any potential close operation to complete
 9734        cx.run_until_parked();
 9735
 9736        // Verify the item remains open (with strikethrough)
 9737        pane.read_with(cx, |pane, _| {
 9738            assert_eq!(
 9739                pane.items().count(),
 9740                1,
 9741                "Item should remain open when close_on_disk_deletion is disabled"
 9742            );
 9743        });
 9744
 9745        // Verify the item shows as deleted
 9746        item.read_with(cx, |item, _| {
 9747            assert!(
 9748                item.has_deleted_file,
 9749                "Item should be marked as having deleted file"
 9750            );
 9751        });
 9752    }
 9753
 9754    /// Tests that dirty files are not automatically closed when deleted from disk,
 9755    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
 9756    /// unsaved changes without being prompted.
 9757    #[gpui::test]
 9758    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
 9759        init_test(cx);
 9760
 9761        // Enable the close_on_file_delete setting
 9762        cx.update_global(|store: &mut SettingsStore, cx| {
 9763            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9764                settings.close_on_file_delete = Some(true);
 9765            });
 9766        });
 9767
 9768        let fs = FakeFs::new(cx.background_executor.clone());
 9769        let project = Project::test(fs, [], cx).await;
 9770        let (workspace, cx) =
 9771            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9772        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9773
 9774        // Create a dirty test item
 9775        let item = cx.new(|cx| {
 9776            TestItem::new(cx)
 9777                .with_dirty(true)
 9778                .with_label("test.txt")
 9779                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9780        });
 9781
 9782        // Add item to workspace
 9783        workspace.update_in(cx, |workspace, window, cx| {
 9784            workspace.add_item(
 9785                pane.clone(),
 9786                Box::new(item.clone()),
 9787                None,
 9788                false,
 9789                false,
 9790                window,
 9791                cx,
 9792            );
 9793        });
 9794
 9795        // Simulate file deletion
 9796        item.update(cx, |item, _| {
 9797            item.set_has_deleted_file(true);
 9798        });
 9799
 9800        // Emit UpdateTab event to trigger the close behavior
 9801        cx.run_until_parked();
 9802        item.update(cx, |_, cx| {
 9803            cx.emit(ItemEvent::UpdateTab);
 9804        });
 9805
 9806        // Allow any potential close operation to complete
 9807        cx.run_until_parked();
 9808
 9809        // Verify the item remains open (dirty files are not auto-closed)
 9810        pane.read_with(cx, |pane, _| {
 9811            assert_eq!(
 9812                pane.items().count(),
 9813                1,
 9814                "Dirty items should not be automatically closed even when file is deleted"
 9815            );
 9816        });
 9817
 9818        // Verify the item is marked as deleted and still dirty
 9819        item.read_with(cx, |item, _| {
 9820            assert!(
 9821                item.has_deleted_file,
 9822                "Item should be marked as having deleted file"
 9823            );
 9824            assert!(item.is_dirty, "Item should still be dirty");
 9825        });
 9826    }
 9827
 9828    /// Tests that navigation history is cleaned up when files are auto-closed
 9829    /// due to deletion from disk.
 9830    #[gpui::test]
 9831    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
 9832        init_test(cx);
 9833
 9834        // Enable the close_on_file_delete setting
 9835        cx.update_global(|store: &mut SettingsStore, cx| {
 9836            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9837                settings.close_on_file_delete = Some(true);
 9838            });
 9839        });
 9840
 9841        let fs = FakeFs::new(cx.background_executor.clone());
 9842        let project = Project::test(fs, [], cx).await;
 9843        let (workspace, cx) =
 9844            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9845        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9846
 9847        // Create test items
 9848        let item1 = cx.new(|cx| {
 9849            TestItem::new(cx)
 9850                .with_label("test1.txt")
 9851                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
 9852        });
 9853        let item1_id = item1.item_id();
 9854
 9855        let item2 = cx.new(|cx| {
 9856            TestItem::new(cx)
 9857                .with_label("test2.txt")
 9858                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
 9859        });
 9860
 9861        // Add items to workspace
 9862        workspace.update_in(cx, |workspace, window, cx| {
 9863            workspace.add_item(
 9864                pane.clone(),
 9865                Box::new(item1.clone()),
 9866                None,
 9867                false,
 9868                false,
 9869                window,
 9870                cx,
 9871            );
 9872            workspace.add_item(
 9873                pane.clone(),
 9874                Box::new(item2.clone()),
 9875                None,
 9876                false,
 9877                false,
 9878                window,
 9879                cx,
 9880            );
 9881        });
 9882
 9883        // Activate item1 to ensure it gets navigation entries
 9884        pane.update_in(cx, |pane, window, cx| {
 9885            pane.activate_item(0, true, true, window, cx);
 9886        });
 9887
 9888        // Switch to item2 and back to create navigation history
 9889        pane.update_in(cx, |pane, window, cx| {
 9890            pane.activate_item(1, true, true, window, cx);
 9891        });
 9892        cx.run_until_parked();
 9893
 9894        pane.update_in(cx, |pane, window, cx| {
 9895            pane.activate_item(0, true, true, window, cx);
 9896        });
 9897        cx.run_until_parked();
 9898
 9899        // Simulate file deletion for item1
 9900        item1.update(cx, |item, _| {
 9901            item.set_has_deleted_file(true);
 9902        });
 9903
 9904        // Emit UpdateTab event to trigger the close behavior
 9905        item1.update(cx, |_, cx| {
 9906            cx.emit(ItemEvent::UpdateTab);
 9907        });
 9908        cx.run_until_parked();
 9909
 9910        // Verify item1 was closed
 9911        pane.read_with(cx, |pane, _| {
 9912            assert_eq!(
 9913                pane.items().count(),
 9914                1,
 9915                "Should have 1 item remaining after auto-close"
 9916            );
 9917        });
 9918
 9919        // Check navigation history after close
 9920        let has_item = pane.read_with(cx, |pane, cx| {
 9921            let mut has_item = false;
 9922            pane.nav_history().for_each_entry(cx, |entry, _| {
 9923                if entry.item.id() == item1_id {
 9924                    has_item = true;
 9925                }
 9926            });
 9927            has_item
 9928        });
 9929
 9930        assert!(
 9931            !has_item,
 9932            "Navigation history should not contain closed item entries"
 9933        );
 9934    }
 9935
 9936    #[gpui::test]
 9937    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
 9938        cx: &mut TestAppContext,
 9939    ) {
 9940        init_test(cx);
 9941
 9942        let fs = FakeFs::new(cx.background_executor.clone());
 9943        let project = Project::test(fs, [], cx).await;
 9944        let (workspace, cx) =
 9945            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9946        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9947
 9948        let dirty_regular_buffer = cx.new(|cx| {
 9949            TestItem::new(cx)
 9950                .with_dirty(true)
 9951                .with_label("1.txt")
 9952                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9953        });
 9954        let dirty_regular_buffer_2 = cx.new(|cx| {
 9955            TestItem::new(cx)
 9956                .with_dirty(true)
 9957                .with_label("2.txt")
 9958                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9959        });
 9960        let clear_regular_buffer = cx.new(|cx| {
 9961            TestItem::new(cx)
 9962                .with_label("3.txt")
 9963                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9964        });
 9965
 9966        let dirty_multi_buffer = cx.new(|cx| {
 9967            TestItem::new(cx)
 9968                .with_dirty(true)
 9969                .with_singleton(false)
 9970                .with_label("Fake Project Search")
 9971                .with_project_items(&[
 9972                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9973                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9974                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9975                ])
 9976        });
 9977        workspace.update_in(cx, |workspace, window, cx| {
 9978            workspace.add_item(
 9979                pane.clone(),
 9980                Box::new(dirty_regular_buffer.clone()),
 9981                None,
 9982                false,
 9983                false,
 9984                window,
 9985                cx,
 9986            );
 9987            workspace.add_item(
 9988                pane.clone(),
 9989                Box::new(dirty_regular_buffer_2.clone()),
 9990                None,
 9991                false,
 9992                false,
 9993                window,
 9994                cx,
 9995            );
 9996            workspace.add_item(
 9997                pane.clone(),
 9998                Box::new(dirty_multi_buffer.clone()),
 9999                None,
10000                false,
10001                false,
10002                window,
10003                cx,
10004            );
10005        });
10006
10007        pane.update_in(cx, |pane, window, cx| {
10008            pane.activate_item(2, true, true, window, cx);
10009            assert_eq!(
10010                pane.active_item().unwrap().item_id(),
10011                dirty_multi_buffer.item_id(),
10012                "Should select the multi buffer in the pane"
10013            );
10014        });
10015        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10016            pane.close_active_item(
10017                &CloseActiveItem {
10018                    save_intent: None,
10019                    close_pinned: false,
10020                },
10021                window,
10022                cx,
10023            )
10024        });
10025        cx.background_executor.run_until_parked();
10026        assert!(
10027            !cx.has_pending_prompt(),
10028            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10029        );
10030        close_multi_buffer_task
10031            .await
10032            .expect("Closing multi buffer failed");
10033        pane.update(cx, |pane, cx| {
10034            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10035            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10036            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10037            assert_eq!(
10038                pane.items()
10039                    .map(|item| item.item_id())
10040                    .sorted()
10041                    .collect::<Vec<_>>(),
10042                vec![
10043                    dirty_regular_buffer.item_id(),
10044                    dirty_regular_buffer_2.item_id(),
10045                ],
10046                "Should have no multi buffer left in the pane"
10047            );
10048            assert!(dirty_regular_buffer.read(cx).is_dirty);
10049            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10050        });
10051    }
10052
10053    #[gpui::test]
10054    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10055        init_test(cx);
10056        let fs = FakeFs::new(cx.executor());
10057        let project = Project::test(fs, [], cx).await;
10058        let (workspace, cx) =
10059            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10060
10061        // Add a new panel to the right dock, opening the dock and setting the
10062        // focus to the new panel.
10063        let panel = workspace.update_in(cx, |workspace, window, cx| {
10064            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10065            workspace.add_panel(panel.clone(), window, cx);
10066
10067            workspace
10068                .right_dock()
10069                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10070
10071            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10072
10073            panel
10074        });
10075
10076        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10077        // panel to the next valid position which, in this case, is the left
10078        // dock.
10079        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10080        workspace.update(cx, |workspace, cx| {
10081            assert!(workspace.left_dock().read(cx).is_open());
10082            assert_eq!(panel.read(cx).position, DockPosition::Left);
10083        });
10084
10085        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10086        // panel to the next valid position which, in this case, is the bottom
10087        // dock.
10088        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10089        workspace.update(cx, |workspace, cx| {
10090            assert!(workspace.bottom_dock().read(cx).is_open());
10091            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10092        });
10093
10094        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10095        // around moving the panel to its initial position, the right dock.
10096        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10097        workspace.update(cx, |workspace, cx| {
10098            assert!(workspace.right_dock().read(cx).is_open());
10099            assert_eq!(panel.read(cx).position, DockPosition::Right);
10100        });
10101
10102        // Remove focus from the panel, ensuring that, if the panel is not
10103        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10104        // the panel's position, so the panel is still in the right dock.
10105        workspace.update_in(cx, |workspace, window, cx| {
10106            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10107        });
10108
10109        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10110        workspace.update(cx, |workspace, cx| {
10111            assert!(workspace.right_dock().read(cx).is_open());
10112            assert_eq!(panel.read(cx).position, DockPosition::Right);
10113        });
10114    }
10115
10116    #[gpui::test]
10117    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10118        init_test(cx);
10119
10120        let fs = FakeFs::new(cx.executor());
10121        let project = Project::test(fs, [], cx).await;
10122        let (workspace, cx) =
10123            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10124
10125        let item_1 = cx.new(|cx| {
10126            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10127        });
10128        workspace.update_in(cx, |workspace, window, cx| {
10129            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10130            workspace.move_item_to_pane_in_direction(
10131                &MoveItemToPaneInDirection {
10132                    direction: SplitDirection::Right,
10133                    focus: true,
10134                    clone: false,
10135                },
10136                window,
10137                cx,
10138            );
10139            workspace.move_item_to_pane_at_index(
10140                &MoveItemToPane {
10141                    destination: 3,
10142                    focus: true,
10143                    clone: false,
10144                },
10145                window,
10146                cx,
10147            );
10148
10149            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10150            assert_eq!(
10151                pane_items_paths(&workspace.active_pane, cx),
10152                vec!["first.txt".to_string()],
10153                "Single item was not moved anywhere"
10154            );
10155        });
10156
10157        let item_2 = cx.new(|cx| {
10158            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10159        });
10160        workspace.update_in(cx, |workspace, window, cx| {
10161            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10162            assert_eq!(
10163                pane_items_paths(&workspace.panes[0], cx),
10164                vec!["first.txt".to_string(), "second.txt".to_string()],
10165            );
10166            workspace.move_item_to_pane_in_direction(
10167                &MoveItemToPaneInDirection {
10168                    direction: SplitDirection::Right,
10169                    focus: true,
10170                    clone: false,
10171                },
10172                window,
10173                cx,
10174            );
10175
10176            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10177            assert_eq!(
10178                pane_items_paths(&workspace.panes[0], cx),
10179                vec!["first.txt".to_string()],
10180                "After moving, one item should be left in the original pane"
10181            );
10182            assert_eq!(
10183                pane_items_paths(&workspace.panes[1], cx),
10184                vec!["second.txt".to_string()],
10185                "New item should have been moved to the new pane"
10186            );
10187        });
10188
10189        let item_3 = cx.new(|cx| {
10190            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10191        });
10192        workspace.update_in(cx, |workspace, window, cx| {
10193            let original_pane = workspace.panes[0].clone();
10194            workspace.set_active_pane(&original_pane, window, cx);
10195            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10196            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10197            assert_eq!(
10198                pane_items_paths(&workspace.active_pane, cx),
10199                vec!["first.txt".to_string(), "third.txt".to_string()],
10200                "New pane should be ready to move one item out"
10201            );
10202
10203            workspace.move_item_to_pane_at_index(
10204                &MoveItemToPane {
10205                    destination: 3,
10206                    focus: true,
10207                    clone: false,
10208                },
10209                window,
10210                cx,
10211            );
10212            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10213            assert_eq!(
10214                pane_items_paths(&workspace.active_pane, cx),
10215                vec!["first.txt".to_string()],
10216                "After moving, one item should be left in the original pane"
10217            );
10218            assert_eq!(
10219                pane_items_paths(&workspace.panes[1], cx),
10220                vec!["second.txt".to_string()],
10221                "Previously created pane should be unchanged"
10222            );
10223            assert_eq!(
10224                pane_items_paths(&workspace.panes[2], cx),
10225                vec!["third.txt".to_string()],
10226                "New item should have been moved to the new pane"
10227            );
10228        });
10229    }
10230
10231    #[gpui::test]
10232    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10233        init_test(cx);
10234
10235        let fs = FakeFs::new(cx.executor());
10236        let project = Project::test(fs, [], cx).await;
10237        let (workspace, cx) =
10238            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10239
10240        let item_1 = cx.new(|cx| {
10241            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10242        });
10243        workspace.update_in(cx, |workspace, window, cx| {
10244            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10245            workspace.move_item_to_pane_in_direction(
10246                &MoveItemToPaneInDirection {
10247                    direction: SplitDirection::Right,
10248                    focus: true,
10249                    clone: true,
10250                },
10251                window,
10252                cx,
10253            );
10254            workspace.move_item_to_pane_at_index(
10255                &MoveItemToPane {
10256                    destination: 3,
10257                    focus: true,
10258                    clone: true,
10259                },
10260                window,
10261                cx,
10262            );
10263
10264            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10265            for pane in workspace.panes() {
10266                assert_eq!(
10267                    pane_items_paths(pane, cx),
10268                    vec!["first.txt".to_string()],
10269                    "Single item exists in all panes"
10270                );
10271            }
10272        });
10273
10274        // verify that the active pane has been updated after waiting for the
10275        // pane focus event to fire and resolve
10276        workspace.read_with(cx, |workspace, _app| {
10277            assert_eq!(
10278                workspace.active_pane(),
10279                &workspace.panes[2],
10280                "The third pane should be the active one: {:?}",
10281                workspace.panes
10282            );
10283        })
10284    }
10285
10286    mod register_project_item_tests {
10287
10288        use super::*;
10289
10290        // View
10291        struct TestPngItemView {
10292            focus_handle: FocusHandle,
10293        }
10294        // Model
10295        struct TestPngItem {}
10296
10297        impl project::ProjectItem for TestPngItem {
10298            fn try_open(
10299                _project: &Entity<Project>,
10300                path: &ProjectPath,
10301                cx: &mut App,
10302            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10303                if path.path.extension().unwrap() == "png" {
10304                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10305                } else {
10306                    None
10307                }
10308            }
10309
10310            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10311                None
10312            }
10313
10314            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10315                None
10316            }
10317
10318            fn is_dirty(&self) -> bool {
10319                false
10320            }
10321        }
10322
10323        impl Item for TestPngItemView {
10324            type Event = ();
10325            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10326                "".into()
10327            }
10328        }
10329        impl EventEmitter<()> for TestPngItemView {}
10330        impl Focusable for TestPngItemView {
10331            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10332                self.focus_handle.clone()
10333            }
10334        }
10335
10336        impl Render for TestPngItemView {
10337            fn render(
10338                &mut self,
10339                _window: &mut Window,
10340                _cx: &mut Context<Self>,
10341            ) -> impl IntoElement {
10342                Empty
10343            }
10344        }
10345
10346        impl ProjectItem for TestPngItemView {
10347            type Item = TestPngItem;
10348
10349            fn for_project_item(
10350                _project: Entity<Project>,
10351                _pane: Option<&Pane>,
10352                _item: Entity<Self::Item>,
10353                _: &mut Window,
10354                cx: &mut Context<Self>,
10355            ) -> Self
10356            where
10357                Self: Sized,
10358            {
10359                Self {
10360                    focus_handle: cx.focus_handle(),
10361                }
10362            }
10363        }
10364
10365        // View
10366        struct TestIpynbItemView {
10367            focus_handle: FocusHandle,
10368        }
10369        // Model
10370        struct TestIpynbItem {}
10371
10372        impl project::ProjectItem for TestIpynbItem {
10373            fn try_open(
10374                _project: &Entity<Project>,
10375                path: &ProjectPath,
10376                cx: &mut App,
10377            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10378                if path.path.extension().unwrap() == "ipynb" {
10379                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10380                } else {
10381                    None
10382                }
10383            }
10384
10385            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10386                None
10387            }
10388
10389            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10390                None
10391            }
10392
10393            fn is_dirty(&self) -> bool {
10394                false
10395            }
10396        }
10397
10398        impl Item for TestIpynbItemView {
10399            type Event = ();
10400            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10401                "".into()
10402            }
10403        }
10404        impl EventEmitter<()> for TestIpynbItemView {}
10405        impl Focusable for TestIpynbItemView {
10406            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10407                self.focus_handle.clone()
10408            }
10409        }
10410
10411        impl Render for TestIpynbItemView {
10412            fn render(
10413                &mut self,
10414                _window: &mut Window,
10415                _cx: &mut Context<Self>,
10416            ) -> impl IntoElement {
10417                Empty
10418            }
10419        }
10420
10421        impl ProjectItem for TestIpynbItemView {
10422            type Item = TestIpynbItem;
10423
10424            fn for_project_item(
10425                _project: Entity<Project>,
10426                _pane: Option<&Pane>,
10427                _item: Entity<Self::Item>,
10428                _: &mut Window,
10429                cx: &mut Context<Self>,
10430            ) -> Self
10431            where
10432                Self: Sized,
10433            {
10434                Self {
10435                    focus_handle: cx.focus_handle(),
10436                }
10437            }
10438        }
10439
10440        struct TestAlternatePngItemView {
10441            focus_handle: FocusHandle,
10442        }
10443
10444        impl Item for TestAlternatePngItemView {
10445            type Event = ();
10446            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10447                "".into()
10448            }
10449        }
10450
10451        impl EventEmitter<()> for TestAlternatePngItemView {}
10452        impl Focusable for TestAlternatePngItemView {
10453            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10454                self.focus_handle.clone()
10455            }
10456        }
10457
10458        impl Render for TestAlternatePngItemView {
10459            fn render(
10460                &mut self,
10461                _window: &mut Window,
10462                _cx: &mut Context<Self>,
10463            ) -> impl IntoElement {
10464                Empty
10465            }
10466        }
10467
10468        impl ProjectItem for TestAlternatePngItemView {
10469            type Item = TestPngItem;
10470
10471            fn for_project_item(
10472                _project: Entity<Project>,
10473                _pane: Option<&Pane>,
10474                _item: Entity<Self::Item>,
10475                _: &mut Window,
10476                cx: &mut Context<Self>,
10477            ) -> Self
10478            where
10479                Self: Sized,
10480            {
10481                Self {
10482                    focus_handle: cx.focus_handle(),
10483                }
10484            }
10485        }
10486
10487        #[gpui::test]
10488        async fn test_register_project_item(cx: &mut TestAppContext) {
10489            init_test(cx);
10490
10491            cx.update(|cx| {
10492                register_project_item::<TestPngItemView>(cx);
10493                register_project_item::<TestIpynbItemView>(cx);
10494            });
10495
10496            let fs = FakeFs::new(cx.executor());
10497            fs.insert_tree(
10498                "/root1",
10499                json!({
10500                    "one.png": "BINARYDATAHERE",
10501                    "two.ipynb": "{ totally a notebook }",
10502                    "three.txt": "editing text, sure why not?"
10503                }),
10504            )
10505            .await;
10506
10507            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10508            let (workspace, cx) =
10509                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10510
10511            let worktree_id = project.update(cx, |project, cx| {
10512                project.worktrees(cx).next().unwrap().read(cx).id()
10513            });
10514
10515            let handle = workspace
10516                .update_in(cx, |workspace, window, cx| {
10517                    let project_path = (worktree_id, "one.png");
10518                    workspace.open_path(project_path, None, true, window, cx)
10519                })
10520                .await
10521                .unwrap();
10522
10523            // Now we can check if the handle we got back errored or not
10524            assert_eq!(
10525                handle.to_any().entity_type(),
10526                TypeId::of::<TestPngItemView>()
10527            );
10528
10529            let handle = workspace
10530                .update_in(cx, |workspace, window, cx| {
10531                    let project_path = (worktree_id, "two.ipynb");
10532                    workspace.open_path(project_path, None, true, window, cx)
10533                })
10534                .await
10535                .unwrap();
10536
10537            assert_eq!(
10538                handle.to_any().entity_type(),
10539                TypeId::of::<TestIpynbItemView>()
10540            );
10541
10542            let handle = workspace
10543                .update_in(cx, |workspace, window, cx| {
10544                    let project_path = (worktree_id, "three.txt");
10545                    workspace.open_path(project_path, None, true, window, cx)
10546                })
10547                .await;
10548            assert!(handle.is_err());
10549        }
10550
10551        #[gpui::test]
10552        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10553            init_test(cx);
10554
10555            cx.update(|cx| {
10556                register_project_item::<TestPngItemView>(cx);
10557                register_project_item::<TestAlternatePngItemView>(cx);
10558            });
10559
10560            let fs = FakeFs::new(cx.executor());
10561            fs.insert_tree(
10562                "/root1",
10563                json!({
10564                    "one.png": "BINARYDATAHERE",
10565                    "two.ipynb": "{ totally a notebook }",
10566                    "three.txt": "editing text, sure why not?"
10567                }),
10568            )
10569            .await;
10570            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10571            let (workspace, cx) =
10572                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10573            let worktree_id = project.update(cx, |project, cx| {
10574                project.worktrees(cx).next().unwrap().read(cx).id()
10575            });
10576
10577            let handle = workspace
10578                .update_in(cx, |workspace, window, cx| {
10579                    let project_path = (worktree_id, "one.png");
10580                    workspace.open_path(project_path, None, true, window, cx)
10581                })
10582                .await
10583                .unwrap();
10584
10585            // This _must_ be the second item registered
10586            assert_eq!(
10587                handle.to_any().entity_type(),
10588                TypeId::of::<TestAlternatePngItemView>()
10589            );
10590
10591            let handle = workspace
10592                .update_in(cx, |workspace, window, cx| {
10593                    let project_path = (worktree_id, "three.txt");
10594                    workspace.open_path(project_path, None, true, window, cx)
10595                })
10596                .await;
10597            assert!(handle.is_err());
10598        }
10599    }
10600
10601    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10602        pane.read(cx)
10603            .items()
10604            .flat_map(|item| {
10605                item.project_paths(cx)
10606                    .into_iter()
10607                    .map(|path| path.path.to_string_lossy().to_string())
10608            })
10609            .collect()
10610    }
10611
10612    pub fn init_test(cx: &mut TestAppContext) {
10613        cx.update(|cx| {
10614            let settings_store = SettingsStore::test(cx);
10615            cx.set_global(settings_store);
10616            theme::init(theme::LoadThemes::JustBase, cx);
10617            language::init(cx);
10618            crate::init_settings(cx);
10619            Project::init_settings(cx);
10620        });
10621    }
10622
10623    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10624        let item = TestProjectItem::new(id, path, cx);
10625        item.update(cx, |item, _| {
10626            item.is_dirty = true;
10627        });
10628        item
10629    }
10630}