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