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