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