workspace.rs

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