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            println!("workspace on_focus_lost");
 1223            let focus_handle = this.focus_handle(cx);
 1224            window.focus(&focus_handle);
 1225        })
 1226        .detach();
 1227
 1228        let weak_handle = cx.entity().downgrade();
 1229        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1230
 1231        let center_pane = cx.new(|cx| {
 1232            let mut center_pane = Pane::new(
 1233                weak_handle.clone(),
 1234                project.clone(),
 1235                pane_history_timestamp.clone(),
 1236                None,
 1237                NewFile.boxed_clone(),
 1238                window,
 1239                cx,
 1240            );
 1241            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1242            center_pane
 1243        });
 1244        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1245            .detach();
 1246
 1247        window.focus(&center_pane.focus_handle(cx));
 1248
 1249        // center_pane.focus_handle(cx).is_focused(window);
 1250
 1251        cx.emit(Event::PaneAdded(center_pane.clone()));
 1252
 1253        let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
 1254        app_state.workspace_store.update(cx, |store, _| {
 1255            store.workspaces.insert(window_handle);
 1256        });
 1257
 1258        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1259        let mut connection_status = app_state.client.status();
 1260        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1261            current_user.next().await;
 1262            connection_status.next().await;
 1263            let mut stream =
 1264                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1265
 1266            while stream.recv().await.is_some() {
 1267                this.update(cx, |_, cx| cx.notify())?;
 1268            }
 1269            anyhow::Ok(())
 1270        });
 1271
 1272        // All leader updates are enqueued and then processed in a single task, so
 1273        // that each asynchronous operation can be run in order.
 1274        let (leader_updates_tx, mut leader_updates_rx) =
 1275            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1276        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1277            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1278                Self::process_leader_update(&this, leader_id, update, cx)
 1279                    .await
 1280                    .log_err();
 1281            }
 1282
 1283            Ok(())
 1284        });
 1285
 1286        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1287        let modal_layer = cx.new(|_| ModalLayer::new());
 1288        let toast_layer = cx.new(|_| ToastLayer::new());
 1289        cx.subscribe(
 1290            &modal_layer,
 1291            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1292                cx.emit(Event::ModalOpened);
 1293            },
 1294        )
 1295        .detach();
 1296
 1297        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 1298        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1299        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1300        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1301        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1302        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1303        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1304        let status_bar = cx.new(|cx| {
 1305            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1306            status_bar.add_left_item(left_dock_buttons, window, cx);
 1307            status_bar.add_right_item(right_dock_buttons, window, cx);
 1308            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1309            status_bar
 1310        });
 1311
 1312        let session_id = app_state.session.read(cx).id().to_owned();
 1313
 1314        let mut active_call = None;
 1315        if let Some(call) = ActiveCall::try_global(cx) {
 1316            let call = call.clone();
 1317            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1318            active_call = Some((call, subscriptions));
 1319        }
 1320
 1321        let (serializable_items_tx, serializable_items_rx) =
 1322            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1323        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1324            Self::serialize_items(&this, serializable_items_rx, cx).await
 1325        });
 1326
 1327        let subscriptions = vec![
 1328            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1329            cx.observe_window_bounds(window, move |this, window, cx| {
 1330                if this.bounds_save_task_queued.is_some() {
 1331                    return;
 1332                }
 1333                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1334                    cx.background_executor()
 1335                        .timer(Duration::from_millis(100))
 1336                        .await;
 1337                    this.update_in(cx, |this, window, cx| {
 1338                        if let Some(display) = window.display(cx) {
 1339                            if let Ok(display_uuid) = display.uuid() {
 1340                                let window_bounds = window.inner_window_bounds();
 1341                                if let Some(database_id) = workspace_id {
 1342                                    cx.background_executor()
 1343                                        .spawn(DB.set_window_open_status(
 1344                                            database_id,
 1345                                            SerializedWindowBounds(window_bounds),
 1346                                            display_uuid,
 1347                                        ))
 1348                                        .detach_and_log_err(cx);
 1349                                }
 1350                            }
 1351                        }
 1352                        this.bounds_save_task_queued.take();
 1353                    })
 1354                    .ok();
 1355                }));
 1356                cx.notify();
 1357            }),
 1358            cx.observe_window_appearance(window, |_, window, cx| {
 1359                let window_appearance = window.appearance();
 1360
 1361                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1362
 1363                ThemeSettings::reload_current_theme(cx);
 1364                ThemeSettings::reload_current_icon_theme(cx);
 1365            }),
 1366            cx.on_release(move |this, cx| {
 1367                this.app_state.workspace_store.update(cx, move |store, _| {
 1368                    store.workspaces.remove(&window_handle.clone());
 1369                })
 1370            }),
 1371        ];
 1372
 1373        cx.defer_in(window, |this, window, cx| {
 1374            this.update_window_title(window, cx);
 1375            this.show_initial_notifications(cx);
 1376        });
 1377        Workspace {
 1378            weak_self: weak_handle.clone(),
 1379            zoomed: None,
 1380            zoomed_position: None,
 1381            previous_dock_drag_coordinates: None,
 1382            center: PaneGroup::new(center_pane.clone()),
 1383            panes: vec![center_pane.clone()],
 1384            panes_by_item: Default::default(),
 1385            active_pane: center_pane.clone(),
 1386            last_active_center_pane: Some(center_pane.downgrade()),
 1387            last_active_view_id: None,
 1388            status_bar,
 1389            modal_layer,
 1390            toast_layer,
 1391            titlebar_item: None,
 1392            notifications: Notifications::default(),
 1393            suppressed_notifications: HashSet::default(),
 1394            left_dock,
 1395            bottom_dock,
 1396            bottom_dock_layout,
 1397            right_dock,
 1398            project: project.clone(),
 1399            follower_states: Default::default(),
 1400            last_leaders_by_pane: Default::default(),
 1401            dispatching_keystrokes: Default::default(),
 1402            window_edited: false,
 1403            dirty_items: Default::default(),
 1404            active_call,
 1405            database_id: workspace_id,
 1406            app_state,
 1407            _observe_current_user,
 1408            _apply_leader_updates,
 1409            _schedule_serialize: None,
 1410            leader_updates_tx,
 1411            _subscriptions: subscriptions,
 1412            pane_history_timestamp,
 1413            workspace_actions: Default::default(),
 1414            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1415            bounds: Default::default(),
 1416            centered_layout: false,
 1417            bounds_save_task_queued: None,
 1418            on_prompt_for_new_path: None,
 1419            on_prompt_for_open_path: None,
 1420            terminal_provider: None,
 1421            debugger_provider: None,
 1422            serializable_items_tx,
 1423            _items_serializer,
 1424            session_id: Some(session_id),
 1425            serialized_ssh_project: None,
 1426        }
 1427    }
 1428
 1429    pub fn new_local(
 1430        abs_paths: Vec<PathBuf>,
 1431        app_state: Arc<AppState>,
 1432        requesting_window: Option<WindowHandle<Workspace>>,
 1433        env: Option<HashMap<String, String>>,
 1434        cx: &mut App,
 1435    ) -> Task<
 1436        anyhow::Result<(
 1437            WindowHandle<Workspace>,
 1438            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1439        )>,
 1440    > {
 1441        let project_handle = Project::local(
 1442            app_state.client.clone(),
 1443            app_state.node_runtime.clone(),
 1444            app_state.user_store.clone(),
 1445            app_state.languages.clone(),
 1446            app_state.fs.clone(),
 1447            env,
 1448            cx,
 1449        );
 1450
 1451        cx.spawn(async move |cx| {
 1452            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1453            for path in abs_paths.into_iter() {
 1454                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1455                    paths_to_open.push(canonical)
 1456                } else {
 1457                    paths_to_open.push(path)
 1458                }
 1459            }
 1460
 1461            let serialized_workspace =
 1462                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1463
 1464            let workspace_location = serialized_workspace
 1465                .as_ref()
 1466                .map(|ws| &ws.location)
 1467                .and_then(|loc| match loc {
 1468                    SerializedWorkspaceLocation::Local(_, order) => {
 1469                        Some((loc.sorted_paths(), order.order()))
 1470                    }
 1471                    _ => None,
 1472                });
 1473
 1474            if let Some((paths, order)) = workspace_location {
 1475                paths_to_open = paths.iter().cloned().collect();
 1476
 1477                if order.iter().enumerate().any(|(i, &j)| i != j) {
 1478                    project_handle
 1479                        .update(cx, |project, cx| {
 1480                            project.set_worktrees_reordered(true, cx);
 1481                        })
 1482                        .log_err();
 1483                }
 1484            }
 1485
 1486            // Get project paths for all of the abs_paths
 1487            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1488                Vec::with_capacity(paths_to_open.len());
 1489
 1490            for path in paths_to_open.into_iter() {
 1491                if let Some((_, project_entry)) = cx
 1492                    .update(|cx| {
 1493                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1494                    })?
 1495                    .await
 1496                    .log_err()
 1497                {
 1498                    project_paths.push((path, Some(project_entry)));
 1499                } else {
 1500                    project_paths.push((path, None));
 1501                }
 1502            }
 1503
 1504            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1505                serialized_workspace.id
 1506            } else {
 1507                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1508            };
 1509
 1510            let toolchains = DB.toolchains(workspace_id).await?;
 1511
 1512            for (toolchain, worktree_id, path) in toolchains {
 1513                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1514                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1515                    continue;
 1516                }
 1517
 1518                project_handle
 1519                    .update(cx, |this, cx| {
 1520                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1521                    })?
 1522                    .await;
 1523            }
 1524            let window = if let Some(window) = requesting_window {
 1525                let centered_layout = serialized_workspace
 1526                    .as_ref()
 1527                    .map(|w| w.centered_layout)
 1528                    .unwrap_or(false);
 1529
 1530                cx.update_window(window.into(), |_, window, cx| {
 1531                    window.replace_root(cx, |window, cx| {
 1532                        let mut workspace = Workspace::new(
 1533                            Some(workspace_id),
 1534                            project_handle.clone(),
 1535                            app_state.clone(),
 1536                            window,
 1537                            cx,
 1538                        );
 1539
 1540                        workspace.centered_layout = centered_layout;
 1541                        workspace
 1542                    });
 1543                })?;
 1544                window
 1545            } else {
 1546                let window_bounds_override = window_bounds_env_override();
 1547
 1548                let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1549                    (Some(WindowBounds::Windowed(bounds)), None)
 1550                } else {
 1551                    let restorable_bounds = serialized_workspace
 1552                        .as_ref()
 1553                        .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 1554                        .or_else(|| {
 1555                            let (display, window_bounds) = DB.last_window().log_err()?;
 1556                            Some((display?, window_bounds?))
 1557                        });
 1558
 1559                    if let Some((serialized_display, serialized_status)) = restorable_bounds {
 1560                        (Some(serialized_status.0), Some(serialized_display))
 1561                    } else {
 1562                        (None, None)
 1563                    }
 1564                };
 1565
 1566                // Use the serialized workspace to construct the new window
 1567                let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
 1568                options.window_bounds = window_bounds;
 1569                let centered_layout = serialized_workspace
 1570                    .as_ref()
 1571                    .map(|w| w.centered_layout)
 1572                    .unwrap_or(false);
 1573                cx.open_window(options, {
 1574                    let app_state = app_state.clone();
 1575                    let project_handle = project_handle.clone();
 1576                    move |window, cx| {
 1577                        cx.new(|cx| {
 1578                            let mut workspace = Workspace::new(
 1579                                Some(workspace_id),
 1580                                project_handle,
 1581                                app_state,
 1582                                window,
 1583                                cx,
 1584                            );
 1585                            workspace.centered_layout = centered_layout;
 1586                            workspace
 1587                        })
 1588                    }
 1589                })?
 1590            };
 1591
 1592            notify_if_database_failed(window, cx);
 1593            let opened_items = window
 1594                .update(cx, |_workspace, window, cx| {
 1595                    open_items(serialized_workspace, project_paths, window, cx)
 1596                })?
 1597                .await
 1598                .unwrap_or_default();
 1599
 1600            window
 1601                .update(cx, |workspace, window, cx| {
 1602                    window.activate_window();
 1603                    workspace.update_history(cx);
 1604                })
 1605                .log_err();
 1606            Ok((window, opened_items))
 1607        })
 1608    }
 1609
 1610    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1611        self.weak_self.clone()
 1612    }
 1613
 1614    pub fn left_dock(&self) -> &Entity<Dock> {
 1615        &self.left_dock
 1616    }
 1617
 1618    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1619        &self.bottom_dock
 1620    }
 1621
 1622    pub fn bottom_dock_layout(&self) -> BottomDockLayout {
 1623        self.bottom_dock_layout
 1624    }
 1625
 1626    pub fn set_bottom_dock_layout(
 1627        &mut self,
 1628        layout: BottomDockLayout,
 1629        window: &mut Window,
 1630        cx: &mut Context<Self>,
 1631    ) {
 1632        let fs = self.project().read(cx).fs();
 1633        settings::update_settings_file::<WorkspaceSettings>(fs.clone(), cx, move |content, _cx| {
 1634            content.bottom_dock_layout = Some(layout);
 1635        });
 1636
 1637        self.bottom_dock_layout = layout;
 1638        cx.notify();
 1639        self.serialize_workspace(window, cx);
 1640    }
 1641
 1642    pub fn right_dock(&self) -> &Entity<Dock> {
 1643        &self.right_dock
 1644    }
 1645
 1646    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1647        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1648    }
 1649
 1650    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1651        match position {
 1652            DockPosition::Left => &self.left_dock,
 1653            DockPosition::Bottom => &self.bottom_dock,
 1654            DockPosition::Right => &self.right_dock,
 1655        }
 1656    }
 1657
 1658    pub fn is_edited(&self) -> bool {
 1659        self.window_edited
 1660    }
 1661
 1662    pub fn add_panel<T: Panel>(
 1663        &mut self,
 1664        panel: Entity<T>,
 1665        window: &mut Window,
 1666        cx: &mut Context<Self>,
 1667    ) {
 1668        let focus_handle = panel.panel_focus_handle(cx);
 1669        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 1670            .detach();
 1671
 1672        let dock_position = panel.position(window, cx);
 1673        let dock = self.dock_at_position(dock_position);
 1674
 1675        dock.update(cx, |dock, cx| {
 1676            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 1677        });
 1678    }
 1679
 1680    pub fn status_bar(&self) -> &Entity<StatusBar> {
 1681        &self.status_bar
 1682    }
 1683
 1684    pub fn app_state(&self) -> &Arc<AppState> {
 1685        &self.app_state
 1686    }
 1687
 1688    pub fn user_store(&self) -> &Entity<UserStore> {
 1689        &self.app_state.user_store
 1690    }
 1691
 1692    pub fn project(&self) -> &Entity<Project> {
 1693        &self.project
 1694    }
 1695
 1696    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 1697        let mut history: HashMap<EntityId, usize> = HashMap::default();
 1698
 1699        for pane_handle in &self.panes {
 1700            let pane = pane_handle.read(cx);
 1701
 1702            for entry in pane.activation_history() {
 1703                history.insert(
 1704                    entry.entity_id,
 1705                    history
 1706                        .get(&entry.entity_id)
 1707                        .cloned()
 1708                        .unwrap_or(0)
 1709                        .max(entry.timestamp),
 1710                );
 1711            }
 1712        }
 1713
 1714        history
 1715    }
 1716
 1717    pub fn recent_navigation_history_iter(
 1718        &self,
 1719        cx: &App,
 1720    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> {
 1721        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 1722        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 1723
 1724        for pane in &self.panes {
 1725            let pane = pane.read(cx);
 1726
 1727            pane.nav_history()
 1728                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 1729                    if let Some(fs_path) = &fs_path {
 1730                        abs_paths_opened
 1731                            .entry(fs_path.clone())
 1732                            .or_default()
 1733                            .insert(project_path.clone());
 1734                    }
 1735                    let timestamp = entry.timestamp;
 1736                    match history.entry(project_path) {
 1737                        hash_map::Entry::Occupied(mut entry) => {
 1738                            let (_, old_timestamp) = entry.get();
 1739                            if &timestamp > old_timestamp {
 1740                                entry.insert((fs_path, timestamp));
 1741                            }
 1742                        }
 1743                        hash_map::Entry::Vacant(entry) => {
 1744                            entry.insert((fs_path, timestamp));
 1745                        }
 1746                    }
 1747                });
 1748
 1749            if let Some(item) = pane.active_item() {
 1750                if let Some(project_path) = item.project_path(cx) {
 1751                    let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 1752
 1753                    if let Some(fs_path) = &fs_path {
 1754                        abs_paths_opened
 1755                            .entry(fs_path.clone())
 1756                            .or_default()
 1757                            .insert(project_path.clone());
 1758                    }
 1759
 1760                    history.insert(project_path, (fs_path, std::usize::MAX));
 1761                }
 1762            }
 1763        }
 1764
 1765        history
 1766            .into_iter()
 1767            .sorted_by_key(|(_, (_, order))| *order)
 1768            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 1769            .rev()
 1770            .filter(move |(history_path, abs_path)| {
 1771                let latest_project_path_opened = abs_path
 1772                    .as_ref()
 1773                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 1774                    .and_then(|project_paths| {
 1775                        project_paths
 1776                            .iter()
 1777                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 1778                    });
 1779
 1780                match latest_project_path_opened {
 1781                    Some(latest_project_path_opened) => latest_project_path_opened == history_path,
 1782                    None => true,
 1783                }
 1784            })
 1785    }
 1786
 1787    pub fn recent_navigation_history(
 1788        &self,
 1789        limit: Option<usize>,
 1790        cx: &App,
 1791    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 1792        self.recent_navigation_history_iter(cx)
 1793            .take(limit.unwrap_or(usize::MAX))
 1794            .collect()
 1795    }
 1796
 1797    fn navigate_history(
 1798        &mut self,
 1799        pane: WeakEntity<Pane>,
 1800        mode: NavigationMode,
 1801        window: &mut Window,
 1802        cx: &mut Context<Workspace>,
 1803    ) -> Task<Result<()>> {
 1804        let to_load = if let Some(pane) = pane.upgrade() {
 1805            pane.update(cx, |pane, cx| {
 1806                window.focus(&pane.focus_handle(cx));
 1807                loop {
 1808                    // Retrieve the weak item handle from the history.
 1809                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 1810
 1811                    // If the item is still present in this pane, then activate it.
 1812                    if let Some(index) = entry
 1813                        .item
 1814                        .upgrade()
 1815                        .and_then(|v| pane.index_for_item(v.as_ref()))
 1816                    {
 1817                        let prev_active_item_index = pane.active_item_index();
 1818                        pane.nav_history_mut().set_mode(mode);
 1819                        pane.activate_item(index, true, true, window, cx);
 1820                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1821
 1822                        let mut navigated = prev_active_item_index != pane.active_item_index();
 1823                        if let Some(data) = entry.data {
 1824                            navigated |= pane.active_item()?.navigate(data, window, cx);
 1825                        }
 1826
 1827                        if navigated {
 1828                            break None;
 1829                        }
 1830                    } else {
 1831                        // If the item is no longer present in this pane, then retrieve its
 1832                        // path info in order to reopen it.
 1833                        break pane
 1834                            .nav_history()
 1835                            .path_for_item(entry.item.id())
 1836                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 1837                    }
 1838                }
 1839            })
 1840        } else {
 1841            None
 1842        };
 1843
 1844        if let Some((project_path, abs_path, entry)) = to_load {
 1845            // If the item was no longer present, then load it again from its previous path, first try the local path
 1846            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 1847
 1848            cx.spawn_in(window, async move  |workspace, cx| {
 1849                let open_by_project_path = open_by_project_path.await;
 1850                let mut navigated = false;
 1851                match open_by_project_path
 1852                    .with_context(|| format!("Navigating to {project_path:?}"))
 1853                {
 1854                    Ok((project_entry_id, build_item)) => {
 1855                        let prev_active_item_id = pane.update(cx, |pane, _| {
 1856                            pane.nav_history_mut().set_mode(mode);
 1857                            pane.active_item().map(|p| p.item_id())
 1858                        })?;
 1859
 1860                        pane.update_in(cx, |pane, window, cx| {
 1861                            let item = pane.open_item(
 1862                                project_entry_id,
 1863                                project_path,
 1864                                true,
 1865                                entry.is_preview,
 1866                                true,
 1867                                None,
 1868                                window, cx,
 1869                                build_item,
 1870                            );
 1871                            navigated |= Some(item.item_id()) != prev_active_item_id;
 1872                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1873                            if let Some(data) = entry.data {
 1874                                navigated |= item.navigate(data, window, cx);
 1875                            }
 1876                        })?;
 1877                    }
 1878                    Err(open_by_project_path_e) => {
 1879                        // Fall back to opening by abs path, in case an external file was opened and closed,
 1880                        // and its worktree is now dropped
 1881                        if let Some(abs_path) = abs_path {
 1882                            let prev_active_item_id = pane.update(cx, |pane, _| {
 1883                                pane.nav_history_mut().set_mode(mode);
 1884                                pane.active_item().map(|p| p.item_id())
 1885                            })?;
 1886                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 1887                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 1888                            })?;
 1889                            match open_by_abs_path
 1890                                .await
 1891                                .with_context(|| format!("Navigating to {abs_path:?}"))
 1892                            {
 1893                                Ok(item) => {
 1894                                    pane.update_in(cx, |pane, window, cx| {
 1895                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 1896                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1897                                        if let Some(data) = entry.data {
 1898                                            navigated |= item.navigate(data, window, cx);
 1899                                        }
 1900                                    })?;
 1901                                }
 1902                                Err(open_by_abs_path_e) => {
 1903                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 1904                                }
 1905                            }
 1906                        }
 1907                    }
 1908                }
 1909
 1910                if !navigated {
 1911                    workspace
 1912                        .update_in(cx, |workspace, window, cx| {
 1913                            Self::navigate_history(workspace, pane, mode, window, cx)
 1914                        })?
 1915                        .await?;
 1916                }
 1917
 1918                Ok(())
 1919            })
 1920        } else {
 1921            Task::ready(Ok(()))
 1922        }
 1923    }
 1924
 1925    pub fn go_back(
 1926        &mut self,
 1927        pane: WeakEntity<Pane>,
 1928        window: &mut Window,
 1929        cx: &mut Context<Workspace>,
 1930    ) -> Task<Result<()>> {
 1931        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 1932    }
 1933
 1934    pub fn go_forward(
 1935        &mut self,
 1936        pane: WeakEntity<Pane>,
 1937        window: &mut Window,
 1938        cx: &mut Context<Workspace>,
 1939    ) -> Task<Result<()>> {
 1940        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 1941    }
 1942
 1943    pub fn reopen_closed_item(
 1944        &mut self,
 1945        window: &mut Window,
 1946        cx: &mut Context<Workspace>,
 1947    ) -> Task<Result<()>> {
 1948        self.navigate_history(
 1949            self.active_pane().downgrade(),
 1950            NavigationMode::ReopeningClosedItem,
 1951            window,
 1952            cx,
 1953        )
 1954    }
 1955
 1956    pub fn client(&self) -> &Arc<Client> {
 1957        &self.app_state.client
 1958    }
 1959
 1960    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 1961        self.titlebar_item = Some(item);
 1962        cx.notify();
 1963    }
 1964
 1965    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 1966        self.on_prompt_for_new_path = Some(prompt)
 1967    }
 1968
 1969    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 1970        self.on_prompt_for_open_path = Some(prompt)
 1971    }
 1972
 1973    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 1974        self.terminal_provider = Some(Box::new(provider));
 1975    }
 1976
 1977    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 1978        self.debugger_provider = Some(Arc::new(provider));
 1979    }
 1980
 1981    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 1982        self.debugger_provider.clone()
 1983    }
 1984
 1985    pub fn serialized_ssh_project(&self) -> Option<SerializedSshProject> {
 1986        self.serialized_ssh_project.clone()
 1987    }
 1988
 1989    pub fn set_serialized_ssh_project(&mut self, serialized_ssh_project: SerializedSshProject) {
 1990        self.serialized_ssh_project = Some(serialized_ssh_project);
 1991    }
 1992
 1993    pub fn prompt_for_open_path(
 1994        &mut self,
 1995        path_prompt_options: PathPromptOptions,
 1996        lister: DirectoryLister,
 1997        window: &mut Window,
 1998        cx: &mut Context<Self>,
 1999    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2000        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2001            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2002            let rx = prompt(self, lister, window, cx);
 2003            self.on_prompt_for_open_path = Some(prompt);
 2004            rx
 2005        } else {
 2006            let (tx, rx) = oneshot::channel();
 2007            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2008
 2009            cx.spawn_in(window, async move |workspace, cx| {
 2010                let Ok(result) = abs_path.await else {
 2011                    return Ok(());
 2012                };
 2013
 2014                match result {
 2015                    Ok(result) => {
 2016                        tx.send(result).ok();
 2017                    }
 2018                    Err(err) => {
 2019                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2020                            workspace.show_portal_error(err.to_string(), cx);
 2021                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2022                            let rx = prompt(workspace, lister, window, cx);
 2023                            workspace.on_prompt_for_open_path = Some(prompt);
 2024                            rx
 2025                        })?;
 2026                        if let Ok(path) = rx.await {
 2027                            tx.send(path).ok();
 2028                        }
 2029                    }
 2030                };
 2031                anyhow::Ok(())
 2032            })
 2033            .detach();
 2034
 2035            rx
 2036        }
 2037    }
 2038
 2039    pub fn prompt_for_new_path(
 2040        &mut self,
 2041        lister: DirectoryLister,
 2042        window: &mut Window,
 2043        cx: &mut Context<Self>,
 2044    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2045        if self.project.read(cx).is_via_collab()
 2046            || self.project.read(cx).is_via_ssh()
 2047            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2048        {
 2049            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2050            let rx = prompt(self, lister, window, cx);
 2051            self.on_prompt_for_new_path = Some(prompt);
 2052            return rx;
 2053        }
 2054
 2055        let (tx, rx) = oneshot::channel();
 2056        cx.spawn_in(window, async move |workspace, cx| {
 2057            let abs_path = workspace.update(cx, |workspace, cx| {
 2058                let relative_to = workspace
 2059                    .most_recent_active_path(cx)
 2060                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2061                    .or_else(|| {
 2062                        let project = workspace.project.read(cx);
 2063                        project.visible_worktrees(cx).find_map(|worktree| {
 2064                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2065                        })
 2066                    })
 2067                    .or_else(std::env::home_dir)
 2068                    .unwrap_or_else(|| PathBuf::from(""));
 2069                cx.prompt_for_new_path(&relative_to)
 2070            })?;
 2071            let abs_path = match abs_path.await? {
 2072                Ok(path) => path,
 2073                Err(err) => {
 2074                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2075                        workspace.show_portal_error(err.to_string(), cx);
 2076
 2077                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2078                        let rx = prompt(workspace, lister, window, cx);
 2079                        workspace.on_prompt_for_new_path = Some(prompt);
 2080                        rx
 2081                    })?;
 2082                    if let Ok(path) = rx.await {
 2083                        tx.send(path).ok();
 2084                    }
 2085                    return anyhow::Ok(());
 2086                }
 2087            };
 2088
 2089            tx.send(abs_path.map(|path| vec![path])).ok();
 2090            anyhow::Ok(())
 2091        })
 2092        .detach();
 2093
 2094        rx
 2095    }
 2096
 2097    pub fn titlebar_item(&self) -> Option<AnyView> {
 2098        self.titlebar_item.clone()
 2099    }
 2100
 2101    /// Call the given callback with a workspace whose project is local.
 2102    ///
 2103    /// If the given workspace has a local project, then it will be passed
 2104    /// to the callback. Otherwise, a new empty window will be created.
 2105    pub fn with_local_workspace<T, F>(
 2106        &mut self,
 2107        window: &mut Window,
 2108        cx: &mut Context<Self>,
 2109        callback: F,
 2110    ) -> Task<Result<T>>
 2111    where
 2112        T: 'static,
 2113        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2114    {
 2115        if self.project.read(cx).is_local() {
 2116            Task::ready(Ok(callback(self, window, cx)))
 2117        } else {
 2118            let env = self.project.read(cx).cli_environment(cx);
 2119            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
 2120            cx.spawn_in(window, async move |_vh, cx| {
 2121                let (workspace, _) = task.await?;
 2122                workspace.update(cx, callback)
 2123            })
 2124        }
 2125    }
 2126
 2127    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2128        self.project.read(cx).worktrees(cx)
 2129    }
 2130
 2131    pub fn visible_worktrees<'a>(
 2132        &self,
 2133        cx: &'a App,
 2134    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2135        self.project.read(cx).visible_worktrees(cx)
 2136    }
 2137
 2138    #[cfg(any(test, feature = "test-support"))]
 2139    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2140        let futures = self
 2141            .worktrees(cx)
 2142            .filter_map(|worktree| worktree.read(cx).as_local())
 2143            .map(|worktree| worktree.scan_complete())
 2144            .collect::<Vec<_>>();
 2145        async move {
 2146            for future in futures {
 2147                future.await;
 2148            }
 2149        }
 2150    }
 2151
 2152    pub fn close_global(_: &CloseWindow, cx: &mut App) {
 2153        cx.defer(|cx| {
 2154            cx.windows().iter().find(|window| {
 2155                window
 2156                    .update(cx, |_, window, _| {
 2157                        if window.is_window_active() {
 2158                            //This can only get called when the window's project connection has been lost
 2159                            //so we don't need to prompt the user for anything and instead just close the window
 2160                            window.remove_window();
 2161                            true
 2162                        } else {
 2163                            false
 2164                        }
 2165                    })
 2166                    .unwrap_or(false)
 2167            });
 2168        });
 2169    }
 2170
 2171    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2172        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2173        cx.spawn_in(window, async move |_, cx| {
 2174            if prepare.await? {
 2175                cx.update(|window, _cx| window.remove_window())?;
 2176            }
 2177            anyhow::Ok(())
 2178        })
 2179        .detach_and_log_err(cx)
 2180    }
 2181
 2182    pub fn move_focused_panel_to_next_position(
 2183        &mut self,
 2184        _: &MoveFocusedPanelToNextPosition,
 2185        window: &mut Window,
 2186        cx: &mut Context<Self>,
 2187    ) {
 2188        let docks = self.all_docks();
 2189        let active_dock = docks
 2190            .into_iter()
 2191            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2192
 2193        if let Some(dock) = active_dock {
 2194            dock.update(cx, |dock, cx| {
 2195                let active_panel = dock
 2196                    .active_panel()
 2197                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2198
 2199                if let Some(panel) = active_panel {
 2200                    panel.move_to_next_position(window, cx);
 2201                }
 2202            })
 2203        }
 2204    }
 2205
 2206    pub fn prepare_to_close(
 2207        &mut self,
 2208        close_intent: CloseIntent,
 2209        window: &mut Window,
 2210        cx: &mut Context<Self>,
 2211    ) -> Task<Result<bool>> {
 2212        let active_call = self.active_call().cloned();
 2213
 2214        // On Linux and Windows, closing the last window should restore the last workspace.
 2215        let save_last_workspace = cfg!(not(target_os = "macos"))
 2216            && close_intent != CloseIntent::ReplaceWindow
 2217            && cx.windows().len() == 1;
 2218
 2219        cx.spawn_in(window, async move |this, cx| {
 2220            let workspace_count = cx.update(|_window, cx| {
 2221                cx.windows()
 2222                    .iter()
 2223                    .filter(|window| window.downcast::<Workspace>().is_some())
 2224                    .count()
 2225            })?;
 2226
 2227            if let Some(active_call) = active_call {
 2228                if close_intent != CloseIntent::Quit
 2229                    && workspace_count == 1
 2230                    && active_call.read_with(cx, |call, _| call.room().is_some())?
 2231                {
 2232                    let answer = cx.update(|window, cx| {
 2233                        window.prompt(
 2234                            PromptLevel::Warning,
 2235                            "Do you want to leave the current call?",
 2236                            None,
 2237                            &["Close window and hang up", "Cancel"],
 2238                            cx,
 2239                        )
 2240                    })?;
 2241
 2242                    if answer.await.log_err() == Some(1) {
 2243                        return anyhow::Ok(false);
 2244                    } else {
 2245                        active_call
 2246                            .update(cx, |call, cx| call.hang_up(cx))?
 2247                            .await
 2248                            .log_err();
 2249                    }
 2250                }
 2251            }
 2252
 2253            let save_result = this
 2254                .update_in(cx, |this, window, cx| {
 2255                    this.save_all_internal(SaveIntent::Close, window, cx)
 2256                })?
 2257                .await;
 2258
 2259            // If we're not quitting, but closing, we remove the workspace from
 2260            // the current session.
 2261            if close_intent != CloseIntent::Quit
 2262                && !save_last_workspace
 2263                && save_result.as_ref().map_or(false, |&res| res)
 2264            {
 2265                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2266                    .await;
 2267            }
 2268
 2269            save_result
 2270        })
 2271    }
 2272
 2273    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2274        self.save_all_internal(
 2275            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2276            window,
 2277            cx,
 2278        )
 2279        .detach_and_log_err(cx);
 2280    }
 2281
 2282    fn send_keystrokes(
 2283        &mut self,
 2284        action: &SendKeystrokes,
 2285        window: &mut Window,
 2286        cx: &mut Context<Self>,
 2287    ) {
 2288        let mut state = self.dispatching_keystrokes.borrow_mut();
 2289        if !state.0.insert(action.0.clone()) {
 2290            cx.propagate();
 2291            return;
 2292        }
 2293        let mut keystrokes: Vec<Keystroke> = action
 2294            .0
 2295            .split(' ')
 2296            .flat_map(|k| Keystroke::parse(k).log_err())
 2297            .collect();
 2298        keystrokes.reverse();
 2299
 2300        state.1.append(&mut keystrokes);
 2301        drop(state);
 2302
 2303        let keystrokes = self.dispatching_keystrokes.clone();
 2304        window
 2305            .spawn(cx, async move |cx| {
 2306                // limit to 100 keystrokes to avoid infinite recursion.
 2307                for _ in 0..100 {
 2308                    let Some(keystroke) = keystrokes.borrow_mut().1.pop() else {
 2309                        keystrokes.borrow_mut().0.clear();
 2310                        return Ok(());
 2311                    };
 2312                    cx.update(|window, cx| {
 2313                        let focused = window.focused(cx);
 2314                        window.dispatch_keystroke(keystroke.clone(), cx);
 2315                        if window.focused(cx) != focused {
 2316                            // dispatch_keystroke may cause the focus to change.
 2317                            // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2318                            // And we need that to happen before the next keystroke to keep vim mode happy...
 2319                            // (Note that the tests always do this implicitly, so you must manually test with something like:
 2320                            //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2321                            // )
 2322                            window.draw(cx).clear();
 2323                        }
 2324                    })?;
 2325                }
 2326
 2327                *keystrokes.borrow_mut() = Default::default();
 2328                anyhow::bail!("over 100 keystrokes passed to send_keystrokes");
 2329            })
 2330            .detach_and_log_err(cx);
 2331    }
 2332
 2333    fn save_all_internal(
 2334        &mut self,
 2335        mut save_intent: SaveIntent,
 2336        window: &mut Window,
 2337        cx: &mut Context<Self>,
 2338    ) -> Task<Result<bool>> {
 2339        if self.project.read(cx).is_disconnected(cx) {
 2340            return Task::ready(Ok(true));
 2341        }
 2342        let dirty_items = self
 2343            .panes
 2344            .iter()
 2345            .flat_map(|pane| {
 2346                pane.read(cx).items().filter_map(|item| {
 2347                    if item.is_dirty(cx) {
 2348                        item.tab_content_text(0, cx);
 2349                        Some((pane.downgrade(), item.boxed_clone()))
 2350                    } else {
 2351                        None
 2352                    }
 2353                })
 2354            })
 2355            .collect::<Vec<_>>();
 2356
 2357        let project = self.project.clone();
 2358        cx.spawn_in(window, async move |workspace, cx| {
 2359            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2360                let (serialize_tasks, remaining_dirty_items) =
 2361                    workspace.update_in(cx, |workspace, window, cx| {
 2362                        let mut remaining_dirty_items = Vec::new();
 2363                        let mut serialize_tasks = Vec::new();
 2364                        for (pane, item) in dirty_items {
 2365                            if let Some(task) = item
 2366                                .to_serializable_item_handle(cx)
 2367                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2368                            {
 2369                                serialize_tasks.push(task);
 2370                            } else {
 2371                                remaining_dirty_items.push((pane, item));
 2372                            }
 2373                        }
 2374                        (serialize_tasks, remaining_dirty_items)
 2375                    })?;
 2376
 2377                futures::future::try_join_all(serialize_tasks).await?;
 2378
 2379                if remaining_dirty_items.len() > 1 {
 2380                    let answer = workspace.update_in(cx, |_, window, cx| {
 2381                        let detail = Pane::file_names_for_prompt(
 2382                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2383                            cx,
 2384                        );
 2385                        window.prompt(
 2386                            PromptLevel::Warning,
 2387                            &"Do you want to save all changes in the following files?",
 2388                            Some(&detail),
 2389                            &["Save all", "Discard all", "Cancel"],
 2390                            cx,
 2391                        )
 2392                    })?;
 2393                    match answer.await.log_err() {
 2394                        Some(0) => save_intent = SaveIntent::SaveAll,
 2395                        Some(1) => save_intent = SaveIntent::Skip,
 2396                        Some(2) => return Ok(false),
 2397                        _ => {}
 2398                    }
 2399                }
 2400
 2401                remaining_dirty_items
 2402            } else {
 2403                dirty_items
 2404            };
 2405
 2406            for (pane, item) in dirty_items {
 2407                let (singleton, project_entry_ids) =
 2408                    cx.update(|_, cx| (item.is_singleton(cx), item.project_entry_ids(cx)))?;
 2409                if singleton || !project_entry_ids.is_empty() {
 2410                    if !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await? {
 2411                        return Ok(false);
 2412                    }
 2413                }
 2414            }
 2415            Ok(true)
 2416        })
 2417    }
 2418
 2419    pub fn open_workspace_for_paths(
 2420        &mut self,
 2421        replace_current_window: bool,
 2422        paths: Vec<PathBuf>,
 2423        window: &mut Window,
 2424        cx: &mut Context<Self>,
 2425    ) -> Task<Result<()>> {
 2426        let window_handle = window.window_handle().downcast::<Self>();
 2427        let is_remote = self.project.read(cx).is_via_collab();
 2428        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2429        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2430
 2431        let window_to_replace = if replace_current_window {
 2432            window_handle
 2433        } else if is_remote || has_worktree || has_dirty_items {
 2434            None
 2435        } else {
 2436            window_handle
 2437        };
 2438        let app_state = self.app_state.clone();
 2439
 2440        cx.spawn(async move |_, cx| {
 2441            cx.update(|cx| {
 2442                open_paths(
 2443                    &paths,
 2444                    app_state,
 2445                    OpenOptions {
 2446                        replace_window: window_to_replace,
 2447                        ..Default::default()
 2448                    },
 2449                    cx,
 2450                )
 2451            })?
 2452            .await?;
 2453            Ok(())
 2454        })
 2455    }
 2456
 2457    #[allow(clippy::type_complexity)]
 2458    pub fn open_paths(
 2459        &mut self,
 2460        mut abs_paths: Vec<PathBuf>,
 2461        options: OpenOptions,
 2462        pane: Option<WeakEntity<Pane>>,
 2463        window: &mut Window,
 2464        cx: &mut Context<Self>,
 2465    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2466        log::info!("open paths {abs_paths:?}");
 2467
 2468        let fs = self.app_state.fs.clone();
 2469
 2470        // Sort the paths to ensure we add worktrees for parents before their children.
 2471        abs_paths.sort_unstable();
 2472        cx.spawn_in(window, async move |this, cx| {
 2473            let mut tasks = Vec::with_capacity(abs_paths.len());
 2474
 2475            for abs_path in &abs_paths {
 2476                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2477                    OpenVisible::All => Some(true),
 2478                    OpenVisible::None => Some(false),
 2479                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2480                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2481                        Some(None) => Some(true),
 2482                        None => None,
 2483                    },
 2484                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2485                        Some(Some(metadata)) => Some(metadata.is_dir),
 2486                        Some(None) => Some(false),
 2487                        None => None,
 2488                    },
 2489                };
 2490                let project_path = match visible {
 2491                    Some(visible) => match this
 2492                        .update(cx, |this, cx| {
 2493                            Workspace::project_path_for_path(
 2494                                this.project.clone(),
 2495                                abs_path,
 2496                                visible,
 2497                                cx,
 2498                            )
 2499                        })
 2500                        .log_err()
 2501                    {
 2502                        Some(project_path) => project_path.await.log_err(),
 2503                        None => None,
 2504                    },
 2505                    None => None,
 2506                };
 2507
 2508                let this = this.clone();
 2509                let abs_path: Arc<Path> = SanitizedPath::from(abs_path.clone()).into();
 2510                let fs = fs.clone();
 2511                let pane = pane.clone();
 2512                let task = cx.spawn(async move |cx| {
 2513                    let (worktree, project_path) = project_path?;
 2514                    if fs.is_dir(&abs_path).await {
 2515                        this.update(cx, |workspace, cx| {
 2516                            let worktree = worktree.read(cx);
 2517                            let worktree_abs_path = worktree.abs_path();
 2518                            let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
 2519                                worktree.root_entry()
 2520                            } else {
 2521                                abs_path
 2522                                    .strip_prefix(worktree_abs_path.as_ref())
 2523                                    .ok()
 2524                                    .and_then(|relative_path| {
 2525                                        worktree.entry_for_path(relative_path)
 2526                                    })
 2527                            }
 2528                            .map(|entry| entry.id);
 2529                            if let Some(entry_id) = entry_id {
 2530                                workspace.project.update(cx, |_, cx| {
 2531                                    cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 2532                                })
 2533                            }
 2534                        })
 2535                        .ok()?;
 2536                        None
 2537                    } else {
 2538                        Some(
 2539                            this.update_in(cx, |this, window, cx| {
 2540                                this.open_path(
 2541                                    project_path,
 2542                                    pane,
 2543                                    options.focus.unwrap_or(true),
 2544                                    window,
 2545                                    cx,
 2546                                )
 2547                            })
 2548                            .ok()?
 2549                            .await,
 2550                        )
 2551                    }
 2552                });
 2553                tasks.push(task);
 2554            }
 2555
 2556            futures::future::join_all(tasks).await
 2557        })
 2558    }
 2559
 2560    pub fn open_resolved_path(
 2561        &mut self,
 2562        path: ResolvedPath,
 2563        window: &mut Window,
 2564        cx: &mut Context<Self>,
 2565    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 2566        match path {
 2567            ResolvedPath::ProjectPath { project_path, .. } => {
 2568                self.open_path(project_path, None, true, window, cx)
 2569            }
 2570            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 2571                path,
 2572                OpenOptions {
 2573                    visible: Some(OpenVisible::None),
 2574                    ..Default::default()
 2575                },
 2576                window,
 2577                cx,
 2578            ),
 2579        }
 2580    }
 2581
 2582    pub fn absolute_path_of_worktree(
 2583        &self,
 2584        worktree_id: WorktreeId,
 2585        cx: &mut Context<Self>,
 2586    ) -> Option<PathBuf> {
 2587        self.project
 2588            .read(cx)
 2589            .worktree_for_id(worktree_id, cx)
 2590            // TODO: use `abs_path` or `root_dir`
 2591            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 2592    }
 2593
 2594    fn add_folder_to_project(
 2595        &mut self,
 2596        _: &AddFolderToProject,
 2597        window: &mut Window,
 2598        cx: &mut Context<Self>,
 2599    ) {
 2600        let project = self.project.read(cx);
 2601        if project.is_via_collab() {
 2602            self.show_error(
 2603                &anyhow!("You cannot add folders to someone else's project"),
 2604                cx,
 2605            );
 2606            return;
 2607        }
 2608        let paths = self.prompt_for_open_path(
 2609            PathPromptOptions {
 2610                files: false,
 2611                directories: true,
 2612                multiple: true,
 2613            },
 2614            DirectoryLister::Project(self.project.clone()),
 2615            window,
 2616            cx,
 2617        );
 2618        cx.spawn_in(window, async move |this, cx| {
 2619            if let Some(paths) = paths.await.log_err().flatten() {
 2620                let results = this
 2621                    .update_in(cx, |this, window, cx| {
 2622                        this.open_paths(
 2623                            paths,
 2624                            OpenOptions {
 2625                                visible: Some(OpenVisible::All),
 2626                                ..Default::default()
 2627                            },
 2628                            None,
 2629                            window,
 2630                            cx,
 2631                        )
 2632                    })?
 2633                    .await;
 2634                for result in results.into_iter().flatten() {
 2635                    result.log_err();
 2636                }
 2637            }
 2638            anyhow::Ok(())
 2639        })
 2640        .detach_and_log_err(cx);
 2641    }
 2642
 2643    pub fn project_path_for_path(
 2644        project: Entity<Project>,
 2645        abs_path: &Path,
 2646        visible: bool,
 2647        cx: &mut App,
 2648    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 2649        let entry = project.update(cx, |project, cx| {
 2650            project.find_or_create_worktree(abs_path, visible, cx)
 2651        });
 2652        cx.spawn(async move |cx| {
 2653            let (worktree, path) = entry.await?;
 2654            let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
 2655            Ok((
 2656                worktree,
 2657                ProjectPath {
 2658                    worktree_id,
 2659                    path: path.into(),
 2660                },
 2661            ))
 2662        })
 2663    }
 2664
 2665    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 2666        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 2667    }
 2668
 2669    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 2670        self.items_of_type(cx).max_by_key(|item| item.item_id())
 2671    }
 2672
 2673    pub fn items_of_type<'a, T: Item>(
 2674        &'a self,
 2675        cx: &'a App,
 2676    ) -> impl 'a + Iterator<Item = Entity<T>> {
 2677        self.panes
 2678            .iter()
 2679            .flat_map(|pane| pane.read(cx).items_of_type())
 2680    }
 2681
 2682    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 2683        self.active_pane().read(cx).active_item()
 2684    }
 2685
 2686    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 2687        let item = self.active_item(cx)?;
 2688        item.to_any().downcast::<I>().ok()
 2689    }
 2690
 2691    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 2692        self.active_item(cx).and_then(|item| item.project_path(cx))
 2693    }
 2694
 2695    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 2696        self.recent_navigation_history_iter(cx)
 2697            .filter_map(|(path, abs_path)| {
 2698                let worktree = self
 2699                    .project
 2700                    .read(cx)
 2701                    .worktree_for_id(path.worktree_id, cx)?;
 2702                if worktree.read(cx).is_visible() {
 2703                    abs_path
 2704                } else {
 2705                    None
 2706                }
 2707            })
 2708            .next()
 2709    }
 2710
 2711    pub fn save_active_item(
 2712        &mut self,
 2713        save_intent: SaveIntent,
 2714        window: &mut Window,
 2715        cx: &mut App,
 2716    ) -> Task<Result<()>> {
 2717        let project = self.project.clone();
 2718        let pane = self.active_pane();
 2719        let item = pane.read(cx).active_item();
 2720        let pane = pane.downgrade();
 2721
 2722        window.spawn(cx, async move |mut cx| {
 2723            if let Some(item) = item {
 2724                Pane::save_item(project, &pane, item.as_ref(), save_intent, &mut cx)
 2725                    .await
 2726                    .map(|_| ())
 2727            } else {
 2728                Ok(())
 2729            }
 2730        })
 2731    }
 2732
 2733    pub fn close_inactive_items_and_panes(
 2734        &mut self,
 2735        action: &CloseInactiveTabsAndPanes,
 2736        window: &mut Window,
 2737        cx: &mut Context<Self>,
 2738    ) {
 2739        if let Some(task) = self.close_all_internal(
 2740            true,
 2741            action.save_intent.unwrap_or(SaveIntent::Close),
 2742            window,
 2743            cx,
 2744        ) {
 2745            task.detach_and_log_err(cx)
 2746        }
 2747    }
 2748
 2749    pub fn close_all_items_and_panes(
 2750        &mut self,
 2751        action: &CloseAllItemsAndPanes,
 2752        window: &mut Window,
 2753        cx: &mut Context<Self>,
 2754    ) {
 2755        if let Some(task) = self.close_all_internal(
 2756            false,
 2757            action.save_intent.unwrap_or(SaveIntent::Close),
 2758            window,
 2759            cx,
 2760        ) {
 2761            task.detach_and_log_err(cx)
 2762        }
 2763    }
 2764
 2765    fn close_all_internal(
 2766        &mut self,
 2767        retain_active_pane: bool,
 2768        save_intent: SaveIntent,
 2769        window: &mut Window,
 2770        cx: &mut Context<Self>,
 2771    ) -> Option<Task<Result<()>>> {
 2772        let current_pane = self.active_pane();
 2773
 2774        let mut tasks = Vec::new();
 2775
 2776        if retain_active_pane {
 2777            let current_pane_close = current_pane.update(cx, |pane, cx| {
 2778                pane.close_inactive_items(
 2779                    &CloseInactiveItems {
 2780                        save_intent: None,
 2781                        close_pinned: false,
 2782                    },
 2783                    window,
 2784                    cx,
 2785                )
 2786            });
 2787
 2788            tasks.push(current_pane_close);
 2789        }
 2790
 2791        for pane in self.panes() {
 2792            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 2793                continue;
 2794            }
 2795
 2796            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 2797                pane.close_all_items(
 2798                    &CloseAllItems {
 2799                        save_intent: Some(save_intent),
 2800                        close_pinned: false,
 2801                    },
 2802                    window,
 2803                    cx,
 2804                )
 2805            });
 2806
 2807            tasks.push(close_pane_items)
 2808        }
 2809
 2810        if tasks.is_empty() {
 2811            None
 2812        } else {
 2813            Some(cx.spawn_in(window, async move |_, _| {
 2814                for task in tasks {
 2815                    task.await?
 2816                }
 2817                Ok(())
 2818            }))
 2819        }
 2820    }
 2821
 2822    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 2823        self.dock_at_position(position).read(cx).is_open()
 2824    }
 2825
 2826    pub fn toggle_dock(
 2827        &mut self,
 2828        dock_side: DockPosition,
 2829        window: &mut Window,
 2830        cx: &mut Context<Self>,
 2831    ) {
 2832        let dock = self.dock_at_position(dock_side);
 2833        let mut focus_center = false;
 2834        let mut reveal_dock = false;
 2835        dock.update(cx, |dock, cx| {
 2836            let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 2837            let was_visible = dock.is_open() && !other_is_zoomed;
 2838            dock.set_open(!was_visible, window, cx);
 2839
 2840            if dock.active_panel().is_none() {
 2841                let Some(panel_ix) = dock
 2842                    .first_enabled_panel_idx(cx)
 2843                    .log_with_level(log::Level::Info)
 2844                else {
 2845                    return;
 2846                };
 2847                dock.activate_panel(panel_ix, window, cx);
 2848            }
 2849
 2850            if let Some(active_panel) = dock.active_panel() {
 2851                if was_visible {
 2852                    if active_panel
 2853                        .panel_focus_handle(cx)
 2854                        .contains_focused(window, cx)
 2855                    {
 2856                        focus_center = true;
 2857                    }
 2858                } else {
 2859                    let focus_handle = &active_panel.panel_focus_handle(cx);
 2860                    window.focus(focus_handle);
 2861                    reveal_dock = true;
 2862                }
 2863            }
 2864        });
 2865
 2866        if reveal_dock {
 2867            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 2868        }
 2869
 2870        if focus_center {
 2871            self.active_pane
 2872                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 2873        }
 2874
 2875        cx.notify();
 2876        self.serialize_workspace(window, cx);
 2877    }
 2878
 2879    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 2880        self.all_docks().into_iter().find(|&dock| {
 2881            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 2882        })
 2883    }
 2884
 2885    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 2886        if let Some(dock) = self.active_dock(window, cx) {
 2887            dock.update(cx, |dock, cx| {
 2888                dock.set_open(false, window, cx);
 2889            });
 2890            return true;
 2891        }
 2892        false
 2893    }
 2894
 2895    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2896        for dock in self.all_docks() {
 2897            dock.update(cx, |dock, cx| {
 2898                dock.set_open(false, window, cx);
 2899            });
 2900        }
 2901
 2902        cx.focus_self(window);
 2903        cx.notify();
 2904        self.serialize_workspace(window, cx);
 2905    }
 2906
 2907    /// Transfer focus to the panel of the given type.
 2908    pub fn focus_panel<T: Panel>(
 2909        &mut self,
 2910        window: &mut Window,
 2911        cx: &mut Context<Self>,
 2912    ) -> Option<Entity<T>> {
 2913        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 2914        panel.to_any().downcast().ok()
 2915    }
 2916
 2917    /// Focus the panel of the given type if it isn't already focused. If it is
 2918    /// already focused, then transfer focus back to the workspace center.
 2919    pub fn toggle_panel_focus<T: Panel>(
 2920        &mut self,
 2921        window: &mut Window,
 2922        cx: &mut Context<Self>,
 2923    ) -> bool {
 2924        let mut did_focus_panel = false;
 2925        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 2926            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 2927            did_focus_panel
 2928        });
 2929        did_focus_panel
 2930    }
 2931
 2932    pub fn activate_panel_for_proto_id(
 2933        &mut self,
 2934        panel_id: PanelId,
 2935        window: &mut Window,
 2936        cx: &mut Context<Self>,
 2937    ) -> Option<Arc<dyn PanelHandle>> {
 2938        let mut panel = None;
 2939        for dock in self.all_docks() {
 2940            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 2941                panel = dock.update(cx, |dock, cx| {
 2942                    dock.activate_panel(panel_index, window, cx);
 2943                    dock.set_open(true, window, cx);
 2944                    dock.active_panel().cloned()
 2945                });
 2946                break;
 2947            }
 2948        }
 2949
 2950        if panel.is_some() {
 2951            cx.notify();
 2952            self.serialize_workspace(window, cx);
 2953        }
 2954
 2955        panel
 2956    }
 2957
 2958    /// Focus or unfocus the given panel type, depending on the given callback.
 2959    fn focus_or_unfocus_panel<T: Panel>(
 2960        &mut self,
 2961        window: &mut Window,
 2962        cx: &mut Context<Self>,
 2963        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 2964    ) -> Option<Arc<dyn PanelHandle>> {
 2965        let mut result_panel = None;
 2966        let mut serialize = false;
 2967        for dock in self.all_docks() {
 2968            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 2969                let mut focus_center = false;
 2970                let panel = dock.update(cx, |dock, cx| {
 2971                    dock.activate_panel(panel_index, window, cx);
 2972
 2973                    let panel = dock.active_panel().cloned();
 2974                    if let Some(panel) = panel.as_ref() {
 2975                        if should_focus(&**panel, window, cx) {
 2976                            dock.set_open(true, window, cx);
 2977                            panel.panel_focus_handle(cx).focus(window);
 2978                        } else {
 2979                            focus_center = true;
 2980                        }
 2981                    }
 2982                    panel
 2983                });
 2984
 2985                if focus_center {
 2986                    self.active_pane
 2987                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 2988                }
 2989
 2990                result_panel = panel;
 2991                serialize = true;
 2992                break;
 2993            }
 2994        }
 2995
 2996        if serialize {
 2997            self.serialize_workspace(window, cx);
 2998        }
 2999
 3000        cx.notify();
 3001        result_panel
 3002    }
 3003
 3004    /// Open the panel of the given type
 3005    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3006        for dock in self.all_docks() {
 3007            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3008                dock.update(cx, |dock, cx| {
 3009                    dock.activate_panel(panel_index, window, cx);
 3010                    dock.set_open(true, window, cx);
 3011                });
 3012            }
 3013        }
 3014    }
 3015
 3016    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3017        self.all_docks()
 3018            .iter()
 3019            .find_map(|dock| dock.read(cx).panel::<T>())
 3020    }
 3021
 3022    fn dismiss_zoomed_items_to_reveal(
 3023        &mut self,
 3024        dock_to_reveal: Option<DockPosition>,
 3025        window: &mut Window,
 3026        cx: &mut Context<Self>,
 3027    ) {
 3028        // If a center pane is zoomed, unzoom it.
 3029        for pane in &self.panes {
 3030            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3031                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3032            }
 3033        }
 3034
 3035        // If another dock is zoomed, hide it.
 3036        let mut focus_center = false;
 3037        for dock in self.all_docks() {
 3038            dock.update(cx, |dock, cx| {
 3039                if Some(dock.position()) != dock_to_reveal {
 3040                    if let Some(panel) = dock.active_panel() {
 3041                        if panel.is_zoomed(window, cx) {
 3042                            focus_center |=
 3043                                panel.panel_focus_handle(cx).contains_focused(window, cx);
 3044                            dock.set_open(false, window, cx);
 3045                        }
 3046                    }
 3047                }
 3048            });
 3049        }
 3050
 3051        if focus_center {
 3052            self.active_pane
 3053                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3054        }
 3055
 3056        if self.zoomed_position != dock_to_reveal {
 3057            self.zoomed = None;
 3058            self.zoomed_position = None;
 3059            cx.emit(Event::ZoomChanged);
 3060        }
 3061
 3062        cx.notify();
 3063    }
 3064
 3065    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3066        let pane = cx.new(|cx| {
 3067            let mut pane = Pane::new(
 3068                self.weak_handle(),
 3069                self.project.clone(),
 3070                self.pane_history_timestamp.clone(),
 3071                None,
 3072                NewFile.boxed_clone(),
 3073                window,
 3074                cx,
 3075            );
 3076            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3077            pane
 3078        });
 3079        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3080            .detach();
 3081        self.panes.push(pane.clone());
 3082
 3083        window.focus(&pane.focus_handle(cx));
 3084
 3085        cx.emit(Event::PaneAdded(pane.clone()));
 3086        pane
 3087    }
 3088
 3089    pub fn add_item_to_center(
 3090        &mut self,
 3091        item: Box<dyn ItemHandle>,
 3092        window: &mut Window,
 3093        cx: &mut Context<Self>,
 3094    ) -> bool {
 3095        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3096            if let Some(center_pane) = center_pane.upgrade() {
 3097                center_pane.update(cx, |pane, cx| {
 3098                    pane.add_item(item, true, true, None, window, cx)
 3099                });
 3100                true
 3101            } else {
 3102                false
 3103            }
 3104        } else {
 3105            false
 3106        }
 3107    }
 3108
 3109    pub fn add_item_to_active_pane(
 3110        &mut self,
 3111        item: Box<dyn ItemHandle>,
 3112        destination_index: Option<usize>,
 3113        focus_item: bool,
 3114        window: &mut Window,
 3115        cx: &mut App,
 3116    ) {
 3117        self.add_item(
 3118            self.active_pane.clone(),
 3119            item,
 3120            destination_index,
 3121            false,
 3122            focus_item,
 3123            window,
 3124            cx,
 3125        )
 3126    }
 3127
 3128    pub fn add_item(
 3129        &mut self,
 3130        pane: Entity<Pane>,
 3131        item: Box<dyn ItemHandle>,
 3132        destination_index: Option<usize>,
 3133        activate_pane: bool,
 3134        focus_item: bool,
 3135        window: &mut Window,
 3136        cx: &mut App,
 3137    ) {
 3138        if let Some(text) = item.telemetry_event_text(cx) {
 3139            telemetry::event!(text);
 3140        }
 3141
 3142        pane.update(cx, |pane, cx| {
 3143            pane.add_item(
 3144                item,
 3145                activate_pane,
 3146                focus_item,
 3147                destination_index,
 3148                window,
 3149                cx,
 3150            )
 3151        });
 3152    }
 3153
 3154    pub fn split_item(
 3155        &mut self,
 3156        split_direction: SplitDirection,
 3157        item: Box<dyn ItemHandle>,
 3158        window: &mut Window,
 3159        cx: &mut Context<Self>,
 3160    ) {
 3161        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3162        self.add_item(new_pane, item, None, true, true, window, cx);
 3163    }
 3164
 3165    pub fn open_abs_path(
 3166        &mut self,
 3167        abs_path: PathBuf,
 3168        options: OpenOptions,
 3169        window: &mut Window,
 3170        cx: &mut Context<Self>,
 3171    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3172        cx.spawn_in(window, async move |workspace, cx| {
 3173            let open_paths_task_result = workspace
 3174                .update_in(cx, |workspace, window, cx| {
 3175                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3176                })
 3177                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3178                .await;
 3179            anyhow::ensure!(
 3180                open_paths_task_result.len() == 1,
 3181                "open abs path {abs_path:?} task returned incorrect number of results"
 3182            );
 3183            match open_paths_task_result
 3184                .into_iter()
 3185                .next()
 3186                .expect("ensured single task result")
 3187            {
 3188                Some(open_result) => {
 3189                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3190                }
 3191                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3192            }
 3193        })
 3194    }
 3195
 3196    pub fn split_abs_path(
 3197        &mut self,
 3198        abs_path: PathBuf,
 3199        visible: bool,
 3200        window: &mut Window,
 3201        cx: &mut Context<Self>,
 3202    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3203        let project_path_task =
 3204            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3205        cx.spawn_in(window, async move |this, cx| {
 3206            let (_, path) = project_path_task.await?;
 3207            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3208                .await
 3209        })
 3210    }
 3211
 3212    pub fn open_path(
 3213        &mut self,
 3214        path: impl Into<ProjectPath>,
 3215        pane: Option<WeakEntity<Pane>>,
 3216        focus_item: bool,
 3217        window: &mut Window,
 3218        cx: &mut App,
 3219    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3220        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3221    }
 3222
 3223    pub fn open_path_preview(
 3224        &mut self,
 3225        path: impl Into<ProjectPath>,
 3226        pane: Option<WeakEntity<Pane>>,
 3227        focus_item: bool,
 3228        allow_preview: bool,
 3229        activate: bool,
 3230        window: &mut Window,
 3231        cx: &mut App,
 3232    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3233        let pane = pane.unwrap_or_else(|| {
 3234            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3235                self.panes
 3236                    .first()
 3237                    .expect("There must be an active pane")
 3238                    .downgrade()
 3239            })
 3240        });
 3241
 3242        let project_path = path.into();
 3243        let task = self.load_path(project_path.clone(), window, cx);
 3244        window.spawn(cx, async move |cx| {
 3245            let (project_entry_id, build_item) = task.await?;
 3246            let result = pane.update_in(cx, |pane, window, cx| {
 3247                pane.open_item(
 3248                    project_entry_id,
 3249                    project_path,
 3250                    focus_item,
 3251                    allow_preview,
 3252                    activate,
 3253                    None,
 3254                    window,
 3255                    cx,
 3256                    build_item,
 3257                )
 3258            });
 3259            result
 3260        })
 3261    }
 3262
 3263    pub fn split_path(
 3264        &mut self,
 3265        path: impl Into<ProjectPath>,
 3266        window: &mut Window,
 3267        cx: &mut Context<Self>,
 3268    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3269        self.split_path_preview(path, false, None, window, cx)
 3270    }
 3271
 3272    pub fn split_path_preview(
 3273        &mut self,
 3274        path: impl Into<ProjectPath>,
 3275        allow_preview: bool,
 3276        split_direction: Option<SplitDirection>,
 3277        window: &mut Window,
 3278        cx: &mut Context<Self>,
 3279    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3280        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3281            self.panes
 3282                .first()
 3283                .expect("There must be an active pane")
 3284                .downgrade()
 3285        });
 3286
 3287        if let Member::Pane(center_pane) = &self.center.root {
 3288            if center_pane.read(cx).items_len() == 0 {
 3289                return self.open_path(path, Some(pane), true, window, cx);
 3290            }
 3291        }
 3292
 3293        let project_path = path.into();
 3294        let task = self.load_path(project_path.clone(), window, cx);
 3295        cx.spawn_in(window, async move |this, cx| {
 3296            let (project_entry_id, build_item) = task.await?;
 3297            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3298                let pane = pane.upgrade()?;
 3299                let new_pane = this.split_pane(
 3300                    pane,
 3301                    split_direction.unwrap_or(SplitDirection::Right),
 3302                    window,
 3303                    cx,
 3304                );
 3305                new_pane.update(cx, |new_pane, cx| {
 3306                    Some(new_pane.open_item(
 3307                        project_entry_id,
 3308                        project_path,
 3309                        true,
 3310                        allow_preview,
 3311                        true,
 3312                        None,
 3313                        window,
 3314                        cx,
 3315                        build_item,
 3316                    ))
 3317                })
 3318            })
 3319            .map(|option| option.context("pane was dropped"))?
 3320        })
 3321    }
 3322
 3323    fn load_path(
 3324        &mut self,
 3325        path: ProjectPath,
 3326        window: &mut Window,
 3327        cx: &mut App,
 3328    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3329        let project = self.project().clone();
 3330        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3331        registry.open_path(&project, &path, window, cx)
 3332    }
 3333
 3334    pub fn find_project_item<T>(
 3335        &self,
 3336        pane: &Entity<Pane>,
 3337        project_item: &Entity<T::Item>,
 3338        cx: &App,
 3339    ) -> Option<Entity<T>>
 3340    where
 3341        T: ProjectItem,
 3342    {
 3343        use project::ProjectItem as _;
 3344        let project_item = project_item.read(cx);
 3345        let entry_id = project_item.entry_id(cx);
 3346        let project_path = project_item.project_path(cx);
 3347
 3348        let mut item = None;
 3349        if let Some(entry_id) = entry_id {
 3350            item = pane.read(cx).item_for_entry(entry_id, cx);
 3351        }
 3352        if item.is_none() {
 3353            if let Some(project_path) = project_path {
 3354                item = pane.read(cx).item_for_path(project_path, cx);
 3355            }
 3356        }
 3357
 3358        item.and_then(|item| item.downcast::<T>())
 3359    }
 3360
 3361    pub fn is_project_item_open<T>(
 3362        &self,
 3363        pane: &Entity<Pane>,
 3364        project_item: &Entity<T::Item>,
 3365        cx: &App,
 3366    ) -> bool
 3367    where
 3368        T: ProjectItem,
 3369    {
 3370        self.find_project_item::<T>(pane, project_item, cx)
 3371            .is_some()
 3372    }
 3373
 3374    pub fn open_project_item<T>(
 3375        &mut self,
 3376        pane: Entity<Pane>,
 3377        project_item: Entity<T::Item>,
 3378        activate_pane: bool,
 3379        focus_item: bool,
 3380        window: &mut Window,
 3381        cx: &mut Context<Self>,
 3382    ) -> Entity<T>
 3383    where
 3384        T: ProjectItem,
 3385    {
 3386        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3387            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3388            return item;
 3389        }
 3390
 3391        let item = pane.update(cx, |pane, cx| {
 3392            cx.new(|cx| {
 3393                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3394            })
 3395        });
 3396        let item_id = item.item_id();
 3397        let mut destination_index = None;
 3398        pane.update(cx, |pane, cx| {
 3399            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 3400                if let Some(preview_item_id) = pane.preview_item_id() {
 3401                    if preview_item_id != item_id {
 3402                        destination_index = pane.close_current_preview_item(window, cx);
 3403                    }
 3404                }
 3405            }
 3406            pane.set_preview_item_id(Some(item.item_id()), cx)
 3407        });
 3408
 3409        self.add_item(
 3410            pane,
 3411            Box::new(item.clone()),
 3412            destination_index,
 3413            activate_pane,
 3414            focus_item,
 3415            window,
 3416            cx,
 3417        );
 3418        item
 3419    }
 3420
 3421    pub fn open_shared_screen(
 3422        &mut self,
 3423        peer_id: PeerId,
 3424        window: &mut Window,
 3425        cx: &mut Context<Self>,
 3426    ) {
 3427        if let Some(shared_screen) =
 3428            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 3429        {
 3430            self.active_pane.update(cx, |pane, cx| {
 3431                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 3432            });
 3433        }
 3434    }
 3435
 3436    pub fn activate_item(
 3437        &mut self,
 3438        item: &dyn ItemHandle,
 3439        activate_pane: bool,
 3440        focus_item: bool,
 3441        window: &mut Window,
 3442        cx: &mut App,
 3443    ) -> bool {
 3444        let result = self.panes.iter().find_map(|pane| {
 3445            pane.read(cx)
 3446                .index_for_item(item)
 3447                .map(|ix| (pane.clone(), ix))
 3448        });
 3449        if let Some((pane, ix)) = result {
 3450            pane.update(cx, |pane, cx| {
 3451                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 3452            });
 3453            true
 3454        } else {
 3455            false
 3456        }
 3457    }
 3458
 3459    fn activate_pane_at_index(
 3460        &mut self,
 3461        action: &ActivatePane,
 3462        window: &mut Window,
 3463        cx: &mut Context<Self>,
 3464    ) {
 3465        let panes = self.center.panes();
 3466        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 3467            window.focus(&pane.focus_handle(cx));
 3468        } else {
 3469            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx);
 3470        }
 3471    }
 3472
 3473    fn move_item_to_pane_at_index(
 3474        &mut self,
 3475        action: &MoveItemToPane,
 3476        window: &mut Window,
 3477        cx: &mut Context<Self>,
 3478    ) {
 3479        let panes = self.center.panes();
 3480        let destination = match panes.get(action.destination) {
 3481            Some(&destination) => destination.clone(),
 3482            None => {
 3483                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3484                    return;
 3485                }
 3486                let direction = SplitDirection::Right;
 3487                let split_off_pane = self
 3488                    .find_pane_in_direction(direction, cx)
 3489                    .unwrap_or_else(|| self.active_pane.clone());
 3490                let new_pane = self.add_pane(window, cx);
 3491                if self
 3492                    .center
 3493                    .split(&split_off_pane, &new_pane, direction)
 3494                    .log_err()
 3495                    .is_none()
 3496                {
 3497                    return;
 3498                };
 3499                new_pane
 3500            }
 3501        };
 3502
 3503        if action.clone {
 3504            clone_active_item(
 3505                self.database_id(),
 3506                &self.active_pane,
 3507                &destination,
 3508                action.focus,
 3509                window,
 3510                cx,
 3511            )
 3512        } else {
 3513            move_active_item(
 3514                &self.active_pane,
 3515                &destination,
 3516                action.focus,
 3517                true,
 3518                window,
 3519                cx,
 3520            )
 3521        }
 3522    }
 3523
 3524    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3525        let panes = self.center.panes();
 3526        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3527            let next_ix = (ix + 1) % panes.len();
 3528            let next_pane = panes[next_ix].clone();
 3529            window.focus(&next_pane.focus_handle(cx));
 3530        }
 3531    }
 3532
 3533    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3534        let panes = self.center.panes();
 3535        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3536            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3537            let prev_pane = panes[prev_ix].clone();
 3538            window.focus(&prev_pane.focus_handle(cx));
 3539        }
 3540    }
 3541
 3542    pub fn activate_pane_in_direction(
 3543        &mut self,
 3544        direction: SplitDirection,
 3545        window: &mut Window,
 3546        cx: &mut App,
 3547    ) {
 3548        use ActivateInDirectionTarget as Target;
 3549        enum Origin {
 3550            LeftDock,
 3551            RightDock,
 3552            BottomDock,
 3553            Center,
 3554        }
 3555
 3556        let origin: Origin = [
 3557            (&self.left_dock, Origin::LeftDock),
 3558            (&self.right_dock, Origin::RightDock),
 3559            (&self.bottom_dock, Origin::BottomDock),
 3560        ]
 3561        .into_iter()
 3562        .find_map(|(dock, origin)| {
 3563            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 3564                Some(origin)
 3565            } else {
 3566                None
 3567            }
 3568        })
 3569        .unwrap_or(Origin::Center);
 3570
 3571        let get_last_active_pane = || {
 3572            let pane = self
 3573                .last_active_center_pane
 3574                .clone()
 3575                .unwrap_or_else(|| {
 3576                    self.panes
 3577                        .first()
 3578                        .expect("There must be an active pane")
 3579                        .downgrade()
 3580                })
 3581                .upgrade()?;
 3582            (pane.read(cx).items_len() != 0).then_some(pane)
 3583        };
 3584
 3585        let try_dock =
 3586            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 3587
 3588        let target = match (origin, direction) {
 3589            // We're in the center, so we first try to go to a different pane,
 3590            // otherwise try to go to a dock.
 3591            (Origin::Center, direction) => {
 3592                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 3593                    Some(Target::Pane(pane))
 3594                } else {
 3595                    match direction {
 3596                        SplitDirection::Up => None,
 3597                        SplitDirection::Down => try_dock(&self.bottom_dock),
 3598                        SplitDirection::Left => try_dock(&self.left_dock),
 3599                        SplitDirection::Right => try_dock(&self.right_dock),
 3600                    }
 3601                }
 3602            }
 3603
 3604            (Origin::LeftDock, SplitDirection::Right) => {
 3605                if let Some(last_active_pane) = get_last_active_pane() {
 3606                    Some(Target::Pane(last_active_pane))
 3607                } else {
 3608                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 3609                }
 3610            }
 3611
 3612            (Origin::LeftDock, SplitDirection::Down)
 3613            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 3614
 3615            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 3616            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 3617            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 3618
 3619            (Origin::RightDock, SplitDirection::Left) => {
 3620                if let Some(last_active_pane) = get_last_active_pane() {
 3621                    Some(Target::Pane(last_active_pane))
 3622                } else {
 3623                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 3624                }
 3625            }
 3626
 3627            _ => None,
 3628        };
 3629
 3630        match target {
 3631            Some(ActivateInDirectionTarget::Pane(pane)) => {
 3632                let pane = pane.read(cx);
 3633                if let Some(item) = pane.active_item() {
 3634                    item.item_focus_handle(cx).focus(window);
 3635                } else {
 3636                    log::error!(
 3637                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 3638                    );
 3639                }
 3640            }
 3641            Some(ActivateInDirectionTarget::Dock(dock)) => {
 3642                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 3643                window.defer(cx, move |window, cx| {
 3644                    let dock = dock.read(cx);
 3645                    if let Some(panel) = dock.active_panel() {
 3646                        panel.panel_focus_handle(cx).focus(window);
 3647                    } else {
 3648                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 3649                    }
 3650                })
 3651            }
 3652            None => {}
 3653        }
 3654    }
 3655
 3656    pub fn move_item_to_pane_in_direction(
 3657        &mut self,
 3658        action: &MoveItemToPaneInDirection,
 3659        window: &mut Window,
 3660        cx: &mut Context<Self>,
 3661    ) {
 3662        let destination = match self.find_pane_in_direction(action.direction, cx) {
 3663            Some(destination) => destination,
 3664            None => {
 3665                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3666                    return;
 3667                }
 3668                let new_pane = self.add_pane(window, cx);
 3669                if self
 3670                    .center
 3671                    .split(&self.active_pane, &new_pane, action.direction)
 3672                    .log_err()
 3673                    .is_none()
 3674                {
 3675                    return;
 3676                };
 3677                new_pane
 3678            }
 3679        };
 3680
 3681        if action.clone {
 3682            clone_active_item(
 3683                self.database_id(),
 3684                &self.active_pane,
 3685                &destination,
 3686                action.focus,
 3687                window,
 3688                cx,
 3689            )
 3690        } else {
 3691            move_active_item(
 3692                &self.active_pane,
 3693                &destination,
 3694                action.focus,
 3695                true,
 3696                window,
 3697                cx,
 3698            );
 3699        }
 3700    }
 3701
 3702    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 3703        self.center.bounding_box_for_pane(pane)
 3704    }
 3705
 3706    pub fn find_pane_in_direction(
 3707        &mut self,
 3708        direction: SplitDirection,
 3709        cx: &App,
 3710    ) -> Option<Entity<Pane>> {
 3711        self.center
 3712            .find_pane_in_direction(&self.active_pane, direction, cx)
 3713            .cloned()
 3714    }
 3715
 3716    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 3717        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 3718            self.center.swap(&self.active_pane, &to);
 3719            cx.notify();
 3720        }
 3721    }
 3722
 3723    pub fn resize_pane(
 3724        &mut self,
 3725        axis: gpui::Axis,
 3726        amount: Pixels,
 3727        window: &mut Window,
 3728        cx: &mut Context<Self>,
 3729    ) {
 3730        let docks = self.all_docks();
 3731        let active_dock = docks
 3732            .into_iter()
 3733            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3734
 3735        if let Some(dock) = active_dock {
 3736            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 3737                return;
 3738            };
 3739            match dock.read(cx).position() {
 3740                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 3741                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 3742                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 3743            }
 3744        } else {
 3745            self.center
 3746                .resize(&self.active_pane, axis, amount, &self.bounds);
 3747        }
 3748        cx.notify();
 3749    }
 3750
 3751    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 3752        self.center.reset_pane_sizes();
 3753        cx.notify();
 3754    }
 3755
 3756    fn handle_pane_focused(
 3757        &mut self,
 3758        pane: Entity<Pane>,
 3759        window: &mut Window,
 3760        cx: &mut Context<Self>,
 3761    ) {
 3762        // This is explicitly hoisted out of the following check for pane identity as
 3763        // terminal panel panes are not registered as a center panes.
 3764        self.status_bar.update(cx, |status_bar, cx| {
 3765            status_bar.set_active_pane(&pane, window, cx);
 3766        });
 3767        if self.active_pane != pane {
 3768            self.set_active_pane(&pane, window, cx);
 3769        }
 3770
 3771        if self.last_active_center_pane.is_none() {
 3772            self.last_active_center_pane = Some(pane.downgrade());
 3773        }
 3774
 3775        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 3776        if pane.read(cx).is_zoomed() {
 3777            self.zoomed = Some(pane.downgrade().into());
 3778        } else {
 3779            self.zoomed = None;
 3780        }
 3781        self.zoomed_position = None;
 3782        cx.emit(Event::ZoomChanged);
 3783        self.update_active_view_for_followers(window, cx);
 3784        pane.update(cx, |pane, _| {
 3785            pane.track_alternate_file_items();
 3786        });
 3787
 3788        cx.notify();
 3789    }
 3790
 3791    fn set_active_pane(
 3792        &mut self,
 3793        pane: &Entity<Pane>,
 3794        window: &mut Window,
 3795        cx: &mut Context<Self>,
 3796    ) {
 3797        self.active_pane = pane.clone();
 3798        self.active_item_path_changed(window, cx);
 3799        self.last_active_center_pane = Some(pane.downgrade());
 3800    }
 3801
 3802    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3803        self.update_active_view_for_followers(window, cx);
 3804    }
 3805
 3806    fn handle_pane_event(
 3807        &mut self,
 3808        pane: &Entity<Pane>,
 3809        event: &pane::Event,
 3810        window: &mut Window,
 3811        cx: &mut Context<Self>,
 3812    ) {
 3813        let mut serialize_workspace = true;
 3814        match event {
 3815            pane::Event::AddItem { item } => {
 3816                item.added_to_pane(self, pane.clone(), window, cx);
 3817                cx.emit(Event::ItemAdded {
 3818                    item: item.boxed_clone(),
 3819                });
 3820            }
 3821            pane::Event::Split(direction) => {
 3822                self.split_and_clone(pane.clone(), *direction, window, cx);
 3823            }
 3824            pane::Event::JoinIntoNext => {
 3825                self.join_pane_into_next(pane.clone(), window, cx);
 3826            }
 3827            pane::Event::JoinAll => {
 3828                self.join_all_panes(window, cx);
 3829            }
 3830            pane::Event::Remove { focus_on_pane } => {
 3831                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 3832            }
 3833            pane::Event::ActivateItem {
 3834                local,
 3835                focus_changed,
 3836            } => {
 3837                cx.on_next_frame(window, |_, window, _| {
 3838                    window.invalidate_character_coordinates();
 3839                });
 3840
 3841                pane.update(cx, |pane, _| {
 3842                    pane.track_alternate_file_items();
 3843                });
 3844                if *local {
 3845                    self.unfollow_in_pane(&pane, window, cx);
 3846                }
 3847                if pane == self.active_pane() {
 3848                    self.active_item_path_changed(window, cx);
 3849                    self.update_active_view_for_followers(window, cx);
 3850                }
 3851                serialize_workspace = *focus_changed || pane != self.active_pane();
 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                window,
 9459                cx,
 9460            )
 9461        });
 9462        cx.background_executor.run_until_parked();
 9463        assert!(!cx.has_pending_prompt());
 9464        close_all_but_multi_buffer_task
 9465            .await
 9466            .expect("Closing all buffers but the multi buffer failed");
 9467        pane.update(cx, |pane, cx| {
 9468            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9469            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9470            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9471            assert_eq!(pane.items_len(), 1);
 9472            assert_eq!(
 9473                pane.active_item().unwrap().item_id(),
 9474                multi_buffer_with_both_files_id,
 9475                "Should have only the multi buffer left in the pane"
 9476            );
 9477            assert!(
 9478                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9479                "The multi buffer containing the unsaved buffer should still be dirty"
 9480            );
 9481        });
 9482
 9483        dirty_regular_buffer.update(cx, |buffer, cx| {
 9484            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9485        });
 9486
 9487        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9488            pane.close_active_item(
 9489                &CloseActiveItem {
 9490                    save_intent: Some(SaveIntent::Close),
 9491                    close_pinned: false,
 9492                },
 9493                window,
 9494                cx,
 9495            )
 9496        });
 9497        cx.background_executor.run_until_parked();
 9498        assert!(
 9499            cx.has_pending_prompt(),
 9500            "Dirty multi buffer should prompt a save dialog"
 9501        );
 9502        cx.simulate_prompt_answer("Save");
 9503        cx.background_executor.run_until_parked();
 9504        close_multi_buffer_task
 9505            .await
 9506            .expect("Closing the multi buffer failed");
 9507        pane.update(cx, |pane, cx| {
 9508            assert_eq!(
 9509                dirty_multi_buffer_with_both.read(cx).save_count,
 9510                1,
 9511                "Multi buffer item should get be saved"
 9512            );
 9513            // Test impl does not save inner items, so we do not assert them
 9514            assert_eq!(
 9515                pane.items_len(),
 9516                0,
 9517                "No more items should be left in the pane"
 9518            );
 9519            assert!(pane.active_item().is_none());
 9520        });
 9521    }
 9522
 9523    #[gpui::test]
 9524    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9525        cx: &mut TestAppContext,
 9526    ) {
 9527        init_test(cx);
 9528
 9529        let fs = FakeFs::new(cx.background_executor.clone());
 9530        let project = Project::test(fs, [], cx).await;
 9531        let (workspace, cx) =
 9532            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9533        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9534
 9535        let dirty_regular_buffer = cx.new(|cx| {
 9536            TestItem::new(cx)
 9537                .with_dirty(true)
 9538                .with_label("1.txt")
 9539                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9540        });
 9541        let dirty_regular_buffer_2 = cx.new(|cx| {
 9542            TestItem::new(cx)
 9543                .with_dirty(true)
 9544                .with_label("2.txt")
 9545                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9546        });
 9547        let clear_regular_buffer = cx.new(|cx| {
 9548            TestItem::new(cx)
 9549                .with_label("3.txt")
 9550                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9551        });
 9552
 9553        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9554            TestItem::new(cx)
 9555                .with_dirty(true)
 9556                .with_singleton(false)
 9557                .with_label("Fake Project Search")
 9558                .with_project_items(&[
 9559                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9560                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9561                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9562                ])
 9563        });
 9564        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9565        workspace.update_in(cx, |workspace, window, cx| {
 9566            workspace.add_item(
 9567                pane.clone(),
 9568                Box::new(dirty_regular_buffer.clone()),
 9569                None,
 9570                false,
 9571                false,
 9572                window,
 9573                cx,
 9574            );
 9575            workspace.add_item(
 9576                pane.clone(),
 9577                Box::new(dirty_multi_buffer_with_both.clone()),
 9578                None,
 9579                false,
 9580                false,
 9581                window,
 9582                cx,
 9583            );
 9584        });
 9585
 9586        pane.update_in(cx, |pane, window, cx| {
 9587            pane.activate_item(1, true, true, window, cx);
 9588            assert_eq!(
 9589                pane.active_item().unwrap().item_id(),
 9590                multi_buffer_with_both_files_id,
 9591                "Should select the multi buffer in the pane"
 9592            );
 9593        });
 9594        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9595            pane.close_active_item(
 9596                &CloseActiveItem {
 9597                    save_intent: None,
 9598                    close_pinned: false,
 9599                },
 9600                window,
 9601                cx,
 9602            )
 9603        });
 9604        cx.background_executor.run_until_parked();
 9605        assert!(
 9606            cx.has_pending_prompt(),
 9607            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9608        );
 9609    }
 9610
 9611    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9612    /// closed when they are deleted from disk.
 9613    #[gpui::test]
 9614    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9615        init_test(cx);
 9616
 9617        // Enable the close_on_disk_deletion setting
 9618        cx.update_global(|store: &mut SettingsStore, cx| {
 9619            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9620                settings.close_on_file_delete = Some(true);
 9621            });
 9622        });
 9623
 9624        let fs = FakeFs::new(cx.background_executor.clone());
 9625        let project = Project::test(fs, [], cx).await;
 9626        let (workspace, cx) =
 9627            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9628        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9629
 9630        // Create a test item that simulates a file
 9631        let item = cx.new(|cx| {
 9632            TestItem::new(cx)
 9633                .with_label("test.txt")
 9634                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9635        });
 9636
 9637        // Add item to workspace
 9638        workspace.update_in(cx, |workspace, window, cx| {
 9639            workspace.add_item(
 9640                pane.clone(),
 9641                Box::new(item.clone()),
 9642                None,
 9643                false,
 9644                false,
 9645                window,
 9646                cx,
 9647            );
 9648        });
 9649
 9650        // Verify the item is in the pane
 9651        pane.read_with(cx, |pane, _| {
 9652            assert_eq!(pane.items().count(), 1);
 9653        });
 9654
 9655        // Simulate file deletion by setting the item's deleted state
 9656        item.update(cx, |item, _| {
 9657            item.set_has_deleted_file(true);
 9658        });
 9659
 9660        // Emit UpdateTab event to trigger the close behavior
 9661        cx.run_until_parked();
 9662        item.update(cx, |_, cx| {
 9663            cx.emit(ItemEvent::UpdateTab);
 9664        });
 9665
 9666        // Allow the close operation to complete
 9667        cx.run_until_parked();
 9668
 9669        // Verify the item was automatically closed
 9670        pane.read_with(cx, |pane, _| {
 9671            assert_eq!(
 9672                pane.items().count(),
 9673                0,
 9674                "Item should be automatically closed when file is deleted"
 9675            );
 9676        });
 9677    }
 9678
 9679    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9680    /// open with a strikethrough when they are deleted from disk.
 9681    #[gpui::test]
 9682    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9683        init_test(cx);
 9684
 9685        // Ensure close_on_disk_deletion is disabled (default)
 9686        cx.update_global(|store: &mut SettingsStore, cx| {
 9687            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9688                settings.close_on_file_delete = Some(false);
 9689            });
 9690        });
 9691
 9692        let fs = FakeFs::new(cx.background_executor.clone());
 9693        let project = Project::test(fs, [], cx).await;
 9694        let (workspace, cx) =
 9695            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9696        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9697
 9698        // Create a test item that simulates a file
 9699        let item = cx.new(|cx| {
 9700            TestItem::new(cx)
 9701                .with_label("test.txt")
 9702                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9703        });
 9704
 9705        // Add item to workspace
 9706        workspace.update_in(cx, |workspace, window, cx| {
 9707            workspace.add_item(
 9708                pane.clone(),
 9709                Box::new(item.clone()),
 9710                None,
 9711                false,
 9712                false,
 9713                window,
 9714                cx,
 9715            );
 9716        });
 9717
 9718        // Verify the item is in the pane
 9719        pane.read_with(cx, |pane, _| {
 9720            assert_eq!(pane.items().count(), 1);
 9721        });
 9722
 9723        // Simulate file deletion
 9724        item.update(cx, |item, _| {
 9725            item.set_has_deleted_file(true);
 9726        });
 9727
 9728        // Emit UpdateTab event
 9729        cx.run_until_parked();
 9730        item.update(cx, |_, cx| {
 9731            cx.emit(ItemEvent::UpdateTab);
 9732        });
 9733
 9734        // Allow any potential close operation to complete
 9735        cx.run_until_parked();
 9736
 9737        // Verify the item remains open (with strikethrough)
 9738        pane.read_with(cx, |pane, _| {
 9739            assert_eq!(
 9740                pane.items().count(),
 9741                1,
 9742                "Item should remain open when close_on_disk_deletion is disabled"
 9743            );
 9744        });
 9745
 9746        // Verify the item shows as deleted
 9747        item.read_with(cx, |item, _| {
 9748            assert!(
 9749                item.has_deleted_file,
 9750                "Item should be marked as having deleted file"
 9751            );
 9752        });
 9753    }
 9754
 9755    /// Tests that dirty files are not automatically closed when deleted from disk,
 9756    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
 9757    /// unsaved changes without being prompted.
 9758    #[gpui::test]
 9759    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
 9760        init_test(cx);
 9761
 9762        // Enable the close_on_file_delete setting
 9763        cx.update_global(|store: &mut SettingsStore, cx| {
 9764            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9765                settings.close_on_file_delete = Some(true);
 9766            });
 9767        });
 9768
 9769        let fs = FakeFs::new(cx.background_executor.clone());
 9770        let project = Project::test(fs, [], cx).await;
 9771        let (workspace, cx) =
 9772            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9773        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9774
 9775        // Create a dirty test item
 9776        let item = cx.new(|cx| {
 9777            TestItem::new(cx)
 9778                .with_dirty(true)
 9779                .with_label("test.txt")
 9780                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9781        });
 9782
 9783        // Add item to workspace
 9784        workspace.update_in(cx, |workspace, window, cx| {
 9785            workspace.add_item(
 9786                pane.clone(),
 9787                Box::new(item.clone()),
 9788                None,
 9789                false,
 9790                false,
 9791                window,
 9792                cx,
 9793            );
 9794        });
 9795
 9796        // Simulate file deletion
 9797        item.update(cx, |item, _| {
 9798            item.set_has_deleted_file(true);
 9799        });
 9800
 9801        // Emit UpdateTab event to trigger the close behavior
 9802        cx.run_until_parked();
 9803        item.update(cx, |_, cx| {
 9804            cx.emit(ItemEvent::UpdateTab);
 9805        });
 9806
 9807        // Allow any potential close operation to complete
 9808        cx.run_until_parked();
 9809
 9810        // Verify the item remains open (dirty files are not auto-closed)
 9811        pane.read_with(cx, |pane, _| {
 9812            assert_eq!(
 9813                pane.items().count(),
 9814                1,
 9815                "Dirty items should not be automatically closed even when file is deleted"
 9816            );
 9817        });
 9818
 9819        // Verify the item is marked as deleted and still dirty
 9820        item.read_with(cx, |item, _| {
 9821            assert!(
 9822                item.has_deleted_file,
 9823                "Item should be marked as having deleted file"
 9824            );
 9825            assert!(item.is_dirty, "Item should still be dirty");
 9826        });
 9827    }
 9828
 9829    /// Tests that navigation history is cleaned up when files are auto-closed
 9830    /// due to deletion from disk.
 9831    #[gpui::test]
 9832    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
 9833        init_test(cx);
 9834
 9835        // Enable the close_on_file_delete setting
 9836        cx.update_global(|store: &mut SettingsStore, cx| {
 9837            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9838                settings.close_on_file_delete = Some(true);
 9839            });
 9840        });
 9841
 9842        let fs = FakeFs::new(cx.background_executor.clone());
 9843        let project = Project::test(fs, [], cx).await;
 9844        let (workspace, cx) =
 9845            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9846        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9847
 9848        // Create test items
 9849        let item1 = cx.new(|cx| {
 9850            TestItem::new(cx)
 9851                .with_label("test1.txt")
 9852                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
 9853        });
 9854        let item1_id = item1.item_id();
 9855
 9856        let item2 = cx.new(|cx| {
 9857            TestItem::new(cx)
 9858                .with_label("test2.txt")
 9859                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
 9860        });
 9861
 9862        // Add items to workspace
 9863        workspace.update_in(cx, |workspace, window, cx| {
 9864            workspace.add_item(
 9865                pane.clone(),
 9866                Box::new(item1.clone()),
 9867                None,
 9868                false,
 9869                false,
 9870                window,
 9871                cx,
 9872            );
 9873            workspace.add_item(
 9874                pane.clone(),
 9875                Box::new(item2.clone()),
 9876                None,
 9877                false,
 9878                false,
 9879                window,
 9880                cx,
 9881            );
 9882        });
 9883
 9884        // Activate item1 to ensure it gets navigation entries
 9885        pane.update_in(cx, |pane, window, cx| {
 9886            pane.activate_item(0, true, true, window, cx);
 9887        });
 9888
 9889        // Switch to item2 and back to create navigation history
 9890        pane.update_in(cx, |pane, window, cx| {
 9891            pane.activate_item(1, true, true, window, cx);
 9892        });
 9893        cx.run_until_parked();
 9894
 9895        pane.update_in(cx, |pane, window, cx| {
 9896            pane.activate_item(0, true, true, window, cx);
 9897        });
 9898        cx.run_until_parked();
 9899
 9900        // Simulate file deletion for item1
 9901        item1.update(cx, |item, _| {
 9902            item.set_has_deleted_file(true);
 9903        });
 9904
 9905        // Emit UpdateTab event to trigger the close behavior
 9906        item1.update(cx, |_, cx| {
 9907            cx.emit(ItemEvent::UpdateTab);
 9908        });
 9909        cx.run_until_parked();
 9910
 9911        // Verify item1 was closed
 9912        pane.read_with(cx, |pane, _| {
 9913            assert_eq!(
 9914                pane.items().count(),
 9915                1,
 9916                "Should have 1 item remaining after auto-close"
 9917            );
 9918        });
 9919
 9920        // Check navigation history after close
 9921        let has_item = pane.read_with(cx, |pane, cx| {
 9922            let mut has_item = false;
 9923            pane.nav_history().for_each_entry(cx, |entry, _| {
 9924                if entry.item.id() == item1_id {
 9925                    has_item = true;
 9926                }
 9927            });
 9928            has_item
 9929        });
 9930
 9931        assert!(
 9932            !has_item,
 9933            "Navigation history should not contain closed item entries"
 9934        );
 9935    }
 9936
 9937    #[gpui::test]
 9938    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
 9939        cx: &mut TestAppContext,
 9940    ) {
 9941        init_test(cx);
 9942
 9943        let fs = FakeFs::new(cx.background_executor.clone());
 9944        let project = Project::test(fs, [], cx).await;
 9945        let (workspace, cx) =
 9946            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9947        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9948
 9949        let dirty_regular_buffer = cx.new(|cx| {
 9950            TestItem::new(cx)
 9951                .with_dirty(true)
 9952                .with_label("1.txt")
 9953                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9954        });
 9955        let dirty_regular_buffer_2 = cx.new(|cx| {
 9956            TestItem::new(cx)
 9957                .with_dirty(true)
 9958                .with_label("2.txt")
 9959                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9960        });
 9961        let clear_regular_buffer = cx.new(|cx| {
 9962            TestItem::new(cx)
 9963                .with_label("3.txt")
 9964                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9965        });
 9966
 9967        let dirty_multi_buffer = cx.new(|cx| {
 9968            TestItem::new(cx)
 9969                .with_dirty(true)
 9970                .with_singleton(false)
 9971                .with_label("Fake Project Search")
 9972                .with_project_items(&[
 9973                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9974                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9975                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9976                ])
 9977        });
 9978        workspace.update_in(cx, |workspace, window, cx| {
 9979            workspace.add_item(
 9980                pane.clone(),
 9981                Box::new(dirty_regular_buffer.clone()),
 9982                None,
 9983                false,
 9984                false,
 9985                window,
 9986                cx,
 9987            );
 9988            workspace.add_item(
 9989                pane.clone(),
 9990                Box::new(dirty_regular_buffer_2.clone()),
 9991                None,
 9992                false,
 9993                false,
 9994                window,
 9995                cx,
 9996            );
 9997            workspace.add_item(
 9998                pane.clone(),
 9999                Box::new(dirty_multi_buffer.clone()),
10000                None,
10001                false,
10002                false,
10003                window,
10004                cx,
10005            );
10006        });
10007
10008        pane.update_in(cx, |pane, window, cx| {
10009            pane.activate_item(2, true, true, window, cx);
10010            assert_eq!(
10011                pane.active_item().unwrap().item_id(),
10012                dirty_multi_buffer.item_id(),
10013                "Should select the multi buffer in the pane"
10014            );
10015        });
10016        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10017            pane.close_active_item(
10018                &CloseActiveItem {
10019                    save_intent: None,
10020                    close_pinned: false,
10021                },
10022                window,
10023                cx,
10024            )
10025        });
10026        cx.background_executor.run_until_parked();
10027        assert!(
10028            !cx.has_pending_prompt(),
10029            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10030        );
10031        close_multi_buffer_task
10032            .await
10033            .expect("Closing multi buffer failed");
10034        pane.update(cx, |pane, cx| {
10035            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10036            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10037            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10038            assert_eq!(
10039                pane.items()
10040                    .map(|item| item.item_id())
10041                    .sorted()
10042                    .collect::<Vec<_>>(),
10043                vec![
10044                    dirty_regular_buffer.item_id(),
10045                    dirty_regular_buffer_2.item_id(),
10046                ],
10047                "Should have no multi buffer left in the pane"
10048            );
10049            assert!(dirty_regular_buffer.read(cx).is_dirty);
10050            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10051        });
10052    }
10053
10054    #[gpui::test]
10055    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10056        init_test(cx);
10057        let fs = FakeFs::new(cx.executor());
10058        let project = Project::test(fs, [], cx).await;
10059        let (workspace, cx) =
10060            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10061
10062        // Add a new panel to the right dock, opening the dock and setting the
10063        // focus to the new panel.
10064        let panel = workspace.update_in(cx, |workspace, window, cx| {
10065            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10066            workspace.add_panel(panel.clone(), window, cx);
10067
10068            workspace
10069                .right_dock()
10070                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10071
10072            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10073
10074            panel
10075        });
10076
10077        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10078        // panel to the next valid position which, in this case, is the left
10079        // dock.
10080        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10081        workspace.update(cx, |workspace, cx| {
10082            assert!(workspace.left_dock().read(cx).is_open());
10083            assert_eq!(panel.read(cx).position, DockPosition::Left);
10084        });
10085
10086        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10087        // panel to the next valid position which, in this case, is the bottom
10088        // dock.
10089        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10090        workspace.update(cx, |workspace, cx| {
10091            assert!(workspace.bottom_dock().read(cx).is_open());
10092            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10093        });
10094
10095        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10096        // around moving the panel to its initial position, the right dock.
10097        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10098        workspace.update(cx, |workspace, cx| {
10099            assert!(workspace.right_dock().read(cx).is_open());
10100            assert_eq!(panel.read(cx).position, DockPosition::Right);
10101        });
10102
10103        // Remove focus from the panel, ensuring that, if the panel is not
10104        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10105        // the panel's position, so the panel is still in the right dock.
10106        workspace.update_in(cx, |workspace, window, cx| {
10107            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10108        });
10109
10110        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10111        workspace.update(cx, |workspace, cx| {
10112            assert!(workspace.right_dock().read(cx).is_open());
10113            assert_eq!(panel.read(cx).position, DockPosition::Right);
10114        });
10115    }
10116
10117    #[gpui::test]
10118    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10119        init_test(cx);
10120
10121        let fs = FakeFs::new(cx.executor());
10122        let project = Project::test(fs, [], cx).await;
10123        let (workspace, cx) =
10124            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10125
10126        let item_1 = cx.new(|cx| {
10127            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10128        });
10129        workspace.update_in(cx, |workspace, window, cx| {
10130            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10131            workspace.move_item_to_pane_in_direction(
10132                &MoveItemToPaneInDirection {
10133                    direction: SplitDirection::Right,
10134                    focus: true,
10135                    clone: false,
10136                },
10137                window,
10138                cx,
10139            );
10140            workspace.move_item_to_pane_at_index(
10141                &MoveItemToPane {
10142                    destination: 3,
10143                    focus: true,
10144                    clone: false,
10145                },
10146                window,
10147                cx,
10148            );
10149
10150            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10151            assert_eq!(
10152                pane_items_paths(&workspace.active_pane, cx),
10153                vec!["first.txt".to_string()],
10154                "Single item was not moved anywhere"
10155            );
10156        });
10157
10158        let item_2 = cx.new(|cx| {
10159            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10160        });
10161        workspace.update_in(cx, |workspace, window, cx| {
10162            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10163            assert_eq!(
10164                pane_items_paths(&workspace.panes[0], cx),
10165                vec!["first.txt".to_string(), "second.txt".to_string()],
10166            );
10167            workspace.move_item_to_pane_in_direction(
10168                &MoveItemToPaneInDirection {
10169                    direction: SplitDirection::Right,
10170                    focus: true,
10171                    clone: false,
10172                },
10173                window,
10174                cx,
10175            );
10176
10177            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10178            assert_eq!(
10179                pane_items_paths(&workspace.panes[0], cx),
10180                vec!["first.txt".to_string()],
10181                "After moving, one item should be left in the original pane"
10182            );
10183            assert_eq!(
10184                pane_items_paths(&workspace.panes[1], cx),
10185                vec!["second.txt".to_string()],
10186                "New item should have been moved to the new pane"
10187            );
10188        });
10189
10190        let item_3 = cx.new(|cx| {
10191            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10192        });
10193        workspace.update_in(cx, |workspace, window, cx| {
10194            let original_pane = workspace.panes[0].clone();
10195            workspace.set_active_pane(&original_pane, window, cx);
10196            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10197            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10198            assert_eq!(
10199                pane_items_paths(&workspace.active_pane, cx),
10200                vec!["first.txt".to_string(), "third.txt".to_string()],
10201                "New pane should be ready to move one item out"
10202            );
10203
10204            workspace.move_item_to_pane_at_index(
10205                &MoveItemToPane {
10206                    destination: 3,
10207                    focus: true,
10208                    clone: false,
10209                },
10210                window,
10211                cx,
10212            );
10213            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10214            assert_eq!(
10215                pane_items_paths(&workspace.active_pane, cx),
10216                vec!["first.txt".to_string()],
10217                "After moving, one item should be left in the original pane"
10218            );
10219            assert_eq!(
10220                pane_items_paths(&workspace.panes[1], cx),
10221                vec!["second.txt".to_string()],
10222                "Previously created pane should be unchanged"
10223            );
10224            assert_eq!(
10225                pane_items_paths(&workspace.panes[2], cx),
10226                vec!["third.txt".to_string()],
10227                "New item should have been moved to the new pane"
10228            );
10229        });
10230    }
10231
10232    #[gpui::test]
10233    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10234        init_test(cx);
10235
10236        let fs = FakeFs::new(cx.executor());
10237        let project = Project::test(fs, [], cx).await;
10238        let (workspace, cx) =
10239            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10240
10241        let item_1 = cx.new(|cx| {
10242            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10243        });
10244        workspace.update_in(cx, |workspace, window, cx| {
10245            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10246            workspace.move_item_to_pane_in_direction(
10247                &MoveItemToPaneInDirection {
10248                    direction: SplitDirection::Right,
10249                    focus: true,
10250                    clone: true,
10251                },
10252                window,
10253                cx,
10254            );
10255            workspace.move_item_to_pane_at_index(
10256                &MoveItemToPane {
10257                    destination: 3,
10258                    focus: true,
10259                    clone: true,
10260                },
10261                window,
10262                cx,
10263            );
10264
10265            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10266            for pane in workspace.panes() {
10267                assert_eq!(
10268                    pane_items_paths(pane, cx),
10269                    vec!["first.txt".to_string()],
10270                    "Single item exists in all panes"
10271                );
10272            }
10273        });
10274
10275        // verify that the active pane has been updated after waiting for the
10276        // pane focus event to fire and resolve
10277        workspace.read_with(cx, |workspace, _app| {
10278            assert_eq!(
10279                workspace.active_pane(),
10280                &workspace.panes[2],
10281                "The third pane should be the active one: {:?}",
10282                workspace.panes
10283            );
10284        })
10285    }
10286
10287    mod register_project_item_tests {
10288
10289        use super::*;
10290
10291        // View
10292        struct TestPngItemView {
10293            focus_handle: FocusHandle,
10294        }
10295        // Model
10296        struct TestPngItem {}
10297
10298        impl project::ProjectItem for TestPngItem {
10299            fn try_open(
10300                _project: &Entity<Project>,
10301                path: &ProjectPath,
10302                cx: &mut App,
10303            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10304                if path.path.extension().unwrap() == "png" {
10305                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10306                } else {
10307                    None
10308                }
10309            }
10310
10311            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10312                None
10313            }
10314
10315            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10316                None
10317            }
10318
10319            fn is_dirty(&self) -> bool {
10320                false
10321            }
10322        }
10323
10324        impl Item for TestPngItemView {
10325            type Event = ();
10326            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10327                "".into()
10328            }
10329        }
10330        impl EventEmitter<()> for TestPngItemView {}
10331        impl Focusable for TestPngItemView {
10332            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10333                self.focus_handle.clone()
10334            }
10335        }
10336
10337        impl Render for TestPngItemView {
10338            fn render(
10339                &mut self,
10340                _window: &mut Window,
10341                _cx: &mut Context<Self>,
10342            ) -> impl IntoElement {
10343                Empty
10344            }
10345        }
10346
10347        impl ProjectItem for TestPngItemView {
10348            type Item = TestPngItem;
10349
10350            fn for_project_item(
10351                _project: Entity<Project>,
10352                _pane: Option<&Pane>,
10353                _item: Entity<Self::Item>,
10354                _: &mut Window,
10355                cx: &mut Context<Self>,
10356            ) -> Self
10357            where
10358                Self: Sized,
10359            {
10360                Self {
10361                    focus_handle: cx.focus_handle(),
10362                }
10363            }
10364        }
10365
10366        // View
10367        struct TestIpynbItemView {
10368            focus_handle: FocusHandle,
10369        }
10370        // Model
10371        struct TestIpynbItem {}
10372
10373        impl project::ProjectItem for TestIpynbItem {
10374            fn try_open(
10375                _project: &Entity<Project>,
10376                path: &ProjectPath,
10377                cx: &mut App,
10378            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10379                if path.path.extension().unwrap() == "ipynb" {
10380                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10381                } else {
10382                    None
10383                }
10384            }
10385
10386            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10387                None
10388            }
10389
10390            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10391                None
10392            }
10393
10394            fn is_dirty(&self) -> bool {
10395                false
10396            }
10397        }
10398
10399        impl Item for TestIpynbItemView {
10400            type Event = ();
10401            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10402                "".into()
10403            }
10404        }
10405        impl EventEmitter<()> for TestIpynbItemView {}
10406        impl Focusable for TestIpynbItemView {
10407            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10408                self.focus_handle.clone()
10409            }
10410        }
10411
10412        impl Render for TestIpynbItemView {
10413            fn render(
10414                &mut self,
10415                _window: &mut Window,
10416                _cx: &mut Context<Self>,
10417            ) -> impl IntoElement {
10418                Empty
10419            }
10420        }
10421
10422        impl ProjectItem for TestIpynbItemView {
10423            type Item = TestIpynbItem;
10424
10425            fn for_project_item(
10426                _project: Entity<Project>,
10427                _pane: Option<&Pane>,
10428                _item: Entity<Self::Item>,
10429                _: &mut Window,
10430                cx: &mut Context<Self>,
10431            ) -> Self
10432            where
10433                Self: Sized,
10434            {
10435                Self {
10436                    focus_handle: cx.focus_handle(),
10437                }
10438            }
10439        }
10440
10441        struct TestAlternatePngItemView {
10442            focus_handle: FocusHandle,
10443        }
10444
10445        impl Item for TestAlternatePngItemView {
10446            type Event = ();
10447            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10448                "".into()
10449            }
10450        }
10451
10452        impl EventEmitter<()> for TestAlternatePngItemView {}
10453        impl Focusable for TestAlternatePngItemView {
10454            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10455                self.focus_handle.clone()
10456            }
10457        }
10458
10459        impl Render for TestAlternatePngItemView {
10460            fn render(
10461                &mut self,
10462                _window: &mut Window,
10463                _cx: &mut Context<Self>,
10464            ) -> impl IntoElement {
10465                Empty
10466            }
10467        }
10468
10469        impl ProjectItem for TestAlternatePngItemView {
10470            type Item = TestPngItem;
10471
10472            fn for_project_item(
10473                _project: Entity<Project>,
10474                _pane: Option<&Pane>,
10475                _item: Entity<Self::Item>,
10476                _: &mut Window,
10477                cx: &mut Context<Self>,
10478            ) -> Self
10479            where
10480                Self: Sized,
10481            {
10482                Self {
10483                    focus_handle: cx.focus_handle(),
10484                }
10485            }
10486        }
10487
10488        #[gpui::test]
10489        async fn test_register_project_item(cx: &mut TestAppContext) {
10490            init_test(cx);
10491
10492            cx.update(|cx| {
10493                register_project_item::<TestPngItemView>(cx);
10494                register_project_item::<TestIpynbItemView>(cx);
10495            });
10496
10497            let fs = FakeFs::new(cx.executor());
10498            fs.insert_tree(
10499                "/root1",
10500                json!({
10501                    "one.png": "BINARYDATAHERE",
10502                    "two.ipynb": "{ totally a notebook }",
10503                    "three.txt": "editing text, sure why not?"
10504                }),
10505            )
10506            .await;
10507
10508            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10509            let (workspace, cx) =
10510                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10511
10512            let worktree_id = project.update(cx, |project, cx| {
10513                project.worktrees(cx).next().unwrap().read(cx).id()
10514            });
10515
10516            let handle = workspace
10517                .update_in(cx, |workspace, window, cx| {
10518                    let project_path = (worktree_id, "one.png");
10519                    workspace.open_path(project_path, None, true, window, cx)
10520                })
10521                .await
10522                .unwrap();
10523
10524            // Now we can check if the handle we got back errored or not
10525            assert_eq!(
10526                handle.to_any().entity_type(),
10527                TypeId::of::<TestPngItemView>()
10528            );
10529
10530            let handle = workspace
10531                .update_in(cx, |workspace, window, cx| {
10532                    let project_path = (worktree_id, "two.ipynb");
10533                    workspace.open_path(project_path, None, true, window, cx)
10534                })
10535                .await
10536                .unwrap();
10537
10538            assert_eq!(
10539                handle.to_any().entity_type(),
10540                TypeId::of::<TestIpynbItemView>()
10541            );
10542
10543            let handle = workspace
10544                .update_in(cx, |workspace, window, cx| {
10545                    let project_path = (worktree_id, "three.txt");
10546                    workspace.open_path(project_path, None, true, window, cx)
10547                })
10548                .await;
10549            assert!(handle.is_err());
10550        }
10551
10552        #[gpui::test]
10553        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10554            init_test(cx);
10555
10556            cx.update(|cx| {
10557                register_project_item::<TestPngItemView>(cx);
10558                register_project_item::<TestAlternatePngItemView>(cx);
10559            });
10560
10561            let fs = FakeFs::new(cx.executor());
10562            fs.insert_tree(
10563                "/root1",
10564                json!({
10565                    "one.png": "BINARYDATAHERE",
10566                    "two.ipynb": "{ totally a notebook }",
10567                    "three.txt": "editing text, sure why not?"
10568                }),
10569            )
10570            .await;
10571            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10572            let (workspace, cx) =
10573                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10574            let worktree_id = project.update(cx, |project, cx| {
10575                project.worktrees(cx).next().unwrap().read(cx).id()
10576            });
10577
10578            let handle = workspace
10579                .update_in(cx, |workspace, window, cx| {
10580                    let project_path = (worktree_id, "one.png");
10581                    workspace.open_path(project_path, None, true, window, cx)
10582                })
10583                .await
10584                .unwrap();
10585
10586            // This _must_ be the second item registered
10587            assert_eq!(
10588                handle.to_any().entity_type(),
10589                TypeId::of::<TestAlternatePngItemView>()
10590            );
10591
10592            let handle = workspace
10593                .update_in(cx, |workspace, window, cx| {
10594                    let project_path = (worktree_id, "three.txt");
10595                    workspace.open_path(project_path, None, true, window, cx)
10596                })
10597                .await;
10598            assert!(handle.is_err());
10599        }
10600    }
10601
10602    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10603        pane.read(cx)
10604            .items()
10605            .flat_map(|item| {
10606                item.project_paths(cx)
10607                    .into_iter()
10608                    .map(|path| path.path.to_string_lossy().to_string())
10609            })
10610            .collect()
10611    }
10612
10613    pub fn init_test(cx: &mut TestAppContext) {
10614        cx.update(|cx| {
10615            let settings_store = SettingsStore::test(cx);
10616            cx.set_global(settings_store);
10617            theme::init(theme::LoadThemes::JustBase, cx);
10618            language::init(cx);
10619            crate::init_settings(cx);
10620            Project::init_settings(cx);
10621        });
10622    }
10623
10624    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10625        let item = TestProjectItem::new(id, path, cx);
10626        item.update(cx, |item, _| {
10627            item.is_dirty = true;
10628        });
10629        item
10630    }
10631}