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