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, Task,
   46    Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId, WindowOptions, actions, canvas,
   47    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        self.last_window_title = Some(title);
 4379    }
 4380
 4381    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4382        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4383        if is_edited != self.window_edited {
 4384            self.window_edited = is_edited;
 4385            window.set_window_edited(self.window_edited)
 4386        }
 4387    }
 4388
 4389    fn update_item_dirty_state(
 4390        &mut self,
 4391        item: &dyn ItemHandle,
 4392        window: &mut Window,
 4393        cx: &mut App,
 4394    ) {
 4395        let is_dirty = item.is_dirty(cx);
 4396        let item_id = item.item_id();
 4397        let was_dirty = self.dirty_items.contains_key(&item_id);
 4398        if is_dirty == was_dirty {
 4399            return;
 4400        }
 4401        if was_dirty {
 4402            self.dirty_items.remove(&item_id);
 4403            self.update_window_edited(window, cx);
 4404            return;
 4405        }
 4406        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4407            let s = item.on_release(
 4408                cx,
 4409                Box::new(move |cx| {
 4410                    window_handle
 4411                        .update(cx, |this, window, cx| {
 4412                            this.dirty_items.remove(&item_id);
 4413                            this.update_window_edited(window, cx)
 4414                        })
 4415                        .ok();
 4416                }),
 4417            );
 4418            self.dirty_items.insert(item_id, s);
 4419            self.update_window_edited(window, cx);
 4420        }
 4421    }
 4422
 4423    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4424        if self.notifications.is_empty() {
 4425            None
 4426        } else {
 4427            Some(
 4428                div()
 4429                    .absolute()
 4430                    .right_3()
 4431                    .bottom_3()
 4432                    .w_112()
 4433                    .h_full()
 4434                    .flex()
 4435                    .flex_col()
 4436                    .justify_end()
 4437                    .gap_2()
 4438                    .children(
 4439                        self.notifications
 4440                            .iter()
 4441                            .map(|(_, notification)| notification.clone().into_any()),
 4442                    ),
 4443            )
 4444        }
 4445    }
 4446
 4447    // RPC handlers
 4448
 4449    fn active_view_for_follower(
 4450        &self,
 4451        follower_project_id: Option<u64>,
 4452        window: &mut Window,
 4453        cx: &mut Context<Self>,
 4454    ) -> Option<proto::View> {
 4455        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4456        let item = item?;
 4457        let leader_id = self
 4458            .pane_for(&*item)
 4459            .and_then(|pane| self.leader_for_pane(&pane));
 4460        let leader_peer_id = match leader_id {
 4461            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4462            Some(CollaboratorId::Agent) | None => None,
 4463        };
 4464
 4465        let item_handle = item.to_followable_item_handle(cx)?;
 4466        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4467        let variant = item_handle.to_state_proto(window, cx)?;
 4468
 4469        if item_handle.is_project_item(window, cx)
 4470            && (follower_project_id.is_none()
 4471                || follower_project_id != self.project.read(cx).remote_id())
 4472        {
 4473            return None;
 4474        }
 4475
 4476        Some(proto::View {
 4477            id: id.to_proto(),
 4478            leader_id: leader_peer_id,
 4479            variant: Some(variant),
 4480            panel_id: panel_id.map(|id| id as i32),
 4481        })
 4482    }
 4483
 4484    fn handle_follow(
 4485        &mut self,
 4486        follower_project_id: Option<u64>,
 4487        window: &mut Window,
 4488        cx: &mut Context<Self>,
 4489    ) -> proto::FollowResponse {
 4490        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4491
 4492        cx.notify();
 4493        proto::FollowResponse {
 4494            // TODO: Remove after version 0.145.x stabilizes.
 4495            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4496            views: active_view.iter().cloned().collect(),
 4497            active_view,
 4498        }
 4499    }
 4500
 4501    fn handle_update_followers(
 4502        &mut self,
 4503        leader_id: PeerId,
 4504        message: proto::UpdateFollowers,
 4505        _window: &mut Window,
 4506        _cx: &mut Context<Self>,
 4507    ) {
 4508        self.leader_updates_tx
 4509            .unbounded_send((leader_id, message))
 4510            .ok();
 4511    }
 4512
 4513    async fn process_leader_update(
 4514        this: &WeakEntity<Self>,
 4515        leader_id: PeerId,
 4516        update: proto::UpdateFollowers,
 4517        cx: &mut AsyncWindowContext,
 4518    ) -> Result<()> {
 4519        match update.variant.context("invalid update")? {
 4520            proto::update_followers::Variant::CreateView(view) => {
 4521                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4522                let should_add_view = this.update(cx, |this, _| {
 4523                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4524                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4525                    } else {
 4526                        anyhow::Ok(false)
 4527                    }
 4528                })??;
 4529
 4530                if should_add_view {
 4531                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4532                }
 4533            }
 4534            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4535                let should_add_view = this.update(cx, |this, _| {
 4536                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4537                        state.active_view_id = update_active_view
 4538                            .view
 4539                            .as_ref()
 4540                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4541
 4542                        if state.active_view_id.is_some_and(|view_id| {
 4543                            !state.items_by_leader_view_id.contains_key(&view_id)
 4544                        }) {
 4545                            anyhow::Ok(true)
 4546                        } else {
 4547                            anyhow::Ok(false)
 4548                        }
 4549                    } else {
 4550                        anyhow::Ok(false)
 4551                    }
 4552                })??;
 4553
 4554                if should_add_view && let Some(view) = update_active_view.view {
 4555                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4556                }
 4557            }
 4558            proto::update_followers::Variant::UpdateView(update_view) => {
 4559                let variant = update_view.variant.context("missing update view variant")?;
 4560                let id = update_view.id.context("missing update view id")?;
 4561                let mut tasks = Vec::new();
 4562                this.update_in(cx, |this, window, cx| {
 4563                    let project = this.project.clone();
 4564                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 4565                        let view_id = ViewId::from_proto(id.clone())?;
 4566                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 4567                            tasks.push(item.view.apply_update_proto(
 4568                                &project,
 4569                                variant.clone(),
 4570                                window,
 4571                                cx,
 4572                            ));
 4573                        }
 4574                    }
 4575                    anyhow::Ok(())
 4576                })??;
 4577                try_join_all(tasks).await.log_err();
 4578            }
 4579        }
 4580        this.update_in(cx, |this, window, cx| {
 4581            this.leader_updated(leader_id, window, cx)
 4582        })?;
 4583        Ok(())
 4584    }
 4585
 4586    async fn add_view_from_leader(
 4587        this: WeakEntity<Self>,
 4588        leader_id: PeerId,
 4589        view: &proto::View,
 4590        cx: &mut AsyncWindowContext,
 4591    ) -> Result<()> {
 4592        let this = this.upgrade().context("workspace dropped")?;
 4593
 4594        let Some(id) = view.id.clone() else {
 4595            anyhow::bail!("no id for view");
 4596        };
 4597        let id = ViewId::from_proto(id)?;
 4598        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 4599
 4600        let pane = this.update(cx, |this, _cx| {
 4601            let state = this
 4602                .follower_states
 4603                .get(&leader_id.into())
 4604                .context("stopped following")?;
 4605            anyhow::Ok(state.pane().clone())
 4606        })??;
 4607        let existing_item = pane.update_in(cx, |pane, window, cx| {
 4608            let client = this.read(cx).client().clone();
 4609            pane.items().find_map(|item| {
 4610                let item = item.to_followable_item_handle(cx)?;
 4611                if item.remote_id(&client, window, cx) == Some(id) {
 4612                    Some(item)
 4613                } else {
 4614                    None
 4615                }
 4616            })
 4617        })?;
 4618        let item = if let Some(existing_item) = existing_item {
 4619            existing_item
 4620        } else {
 4621            let variant = view.variant.clone();
 4622            anyhow::ensure!(variant.is_some(), "missing view variant");
 4623
 4624            let task = cx.update(|window, cx| {
 4625                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 4626            })?;
 4627
 4628            let Some(task) = task else {
 4629                anyhow::bail!(
 4630                    "failed to construct view from leader (maybe from a different version of zed?)"
 4631                );
 4632            };
 4633
 4634            let mut new_item = task.await?;
 4635            pane.update_in(cx, |pane, window, cx| {
 4636                let mut item_to_remove = None;
 4637                for (ix, item) in pane.items().enumerate() {
 4638                    if let Some(item) = item.to_followable_item_handle(cx) {
 4639                        match new_item.dedup(item.as_ref(), window, cx) {
 4640                            Some(item::Dedup::KeepExisting) => {
 4641                                new_item =
 4642                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 4643                                break;
 4644                            }
 4645                            Some(item::Dedup::ReplaceExisting) => {
 4646                                item_to_remove = Some((ix, item.item_id()));
 4647                                break;
 4648                            }
 4649                            None => {}
 4650                        }
 4651                    }
 4652                }
 4653
 4654                if let Some((ix, id)) = item_to_remove {
 4655                    pane.remove_item(id, false, false, window, cx);
 4656                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 4657                }
 4658            })?;
 4659
 4660            new_item
 4661        };
 4662
 4663        this.update_in(cx, |this, window, cx| {
 4664            let state = this.follower_states.get_mut(&leader_id.into())?;
 4665            item.set_leader_id(Some(leader_id.into()), window, cx);
 4666            state.items_by_leader_view_id.insert(
 4667                id,
 4668                FollowerView {
 4669                    view: item,
 4670                    location: panel_id,
 4671                },
 4672            );
 4673
 4674            Some(())
 4675        })?;
 4676
 4677        Ok(())
 4678    }
 4679
 4680    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4681        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 4682            return;
 4683        };
 4684
 4685        if let Some(agent_location) = self.project.read(cx).agent_location() {
 4686            let buffer_entity_id = agent_location.buffer.entity_id();
 4687            let view_id = ViewId {
 4688                creator: CollaboratorId::Agent,
 4689                id: buffer_entity_id.as_u64(),
 4690            };
 4691            follower_state.active_view_id = Some(view_id);
 4692
 4693            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 4694                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 4695                hash_map::Entry::Vacant(entry) => {
 4696                    let existing_view =
 4697                        follower_state
 4698                            .center_pane
 4699                            .read(cx)
 4700                            .items()
 4701                            .find_map(|item| {
 4702                                let item = item.to_followable_item_handle(cx)?;
 4703                                if item.is_singleton(cx)
 4704                                    && item.project_item_model_ids(cx).as_slice()
 4705                                        == [buffer_entity_id]
 4706                                {
 4707                                    Some(item)
 4708                                } else {
 4709                                    None
 4710                                }
 4711                            });
 4712                    let view = existing_view.or_else(|| {
 4713                        agent_location.buffer.upgrade().and_then(|buffer| {
 4714                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 4715                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 4716                            })?
 4717                            .to_followable_item_handle(cx)
 4718                        })
 4719                    });
 4720
 4721                    view.map(|view| {
 4722                        entry.insert(FollowerView {
 4723                            view,
 4724                            location: None,
 4725                        })
 4726                    })
 4727                }
 4728            };
 4729
 4730            if let Some(item) = item {
 4731                item.view
 4732                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 4733                item.view
 4734                    .update_agent_location(agent_location.position, window, cx);
 4735            }
 4736        } else {
 4737            follower_state.active_view_id = None;
 4738        }
 4739
 4740        self.leader_updated(CollaboratorId::Agent, window, cx);
 4741    }
 4742
 4743    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 4744        let mut is_project_item = true;
 4745        let mut update = proto::UpdateActiveView::default();
 4746        if window.is_window_active() {
 4747            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 4748
 4749            if let Some(item) = active_item
 4750                && item.item_focus_handle(cx).contains_focused(window, cx)
 4751            {
 4752                let leader_id = self
 4753                    .pane_for(&*item)
 4754                    .and_then(|pane| self.leader_for_pane(&pane));
 4755                let leader_peer_id = match leader_id {
 4756                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4757                    Some(CollaboratorId::Agent) | None => None,
 4758                };
 4759
 4760                if let Some(item) = item.to_followable_item_handle(cx) {
 4761                    let id = item
 4762                        .remote_id(&self.app_state.client, window, cx)
 4763                        .map(|id| id.to_proto());
 4764
 4765                    if let Some(id) = id
 4766                        && let Some(variant) = item.to_state_proto(window, cx)
 4767                    {
 4768                        let view = Some(proto::View {
 4769                            id: id.clone(),
 4770                            leader_id: leader_peer_id,
 4771                            variant: Some(variant),
 4772                            panel_id: panel_id.map(|id| id as i32),
 4773                        });
 4774
 4775                        is_project_item = item.is_project_item(window, cx);
 4776                        update = proto::UpdateActiveView {
 4777                            view,
 4778                            // TODO: Remove after version 0.145.x stabilizes.
 4779                            id,
 4780                            leader_id: leader_peer_id,
 4781                        };
 4782                    };
 4783                }
 4784            }
 4785        }
 4786
 4787        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 4788        if active_view_id != self.last_active_view_id.as_ref() {
 4789            self.last_active_view_id = active_view_id.cloned();
 4790            self.update_followers(
 4791                is_project_item,
 4792                proto::update_followers::Variant::UpdateActiveView(update),
 4793                window,
 4794                cx,
 4795            );
 4796        }
 4797    }
 4798
 4799    fn active_item_for_followers(
 4800        &self,
 4801        window: &mut Window,
 4802        cx: &mut App,
 4803    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 4804        let mut active_item = None;
 4805        let mut panel_id = None;
 4806        for dock in self.all_docks() {
 4807            if dock.focus_handle(cx).contains_focused(window, cx)
 4808                && let Some(panel) = dock.read(cx).active_panel()
 4809                && let Some(pane) = panel.pane(cx)
 4810                && let Some(item) = pane.read(cx).active_item()
 4811            {
 4812                active_item = Some(item);
 4813                panel_id = panel.remote_id();
 4814                break;
 4815            }
 4816        }
 4817
 4818        if active_item.is_none() {
 4819            active_item = self.active_pane().read(cx).active_item();
 4820        }
 4821        (active_item, panel_id)
 4822    }
 4823
 4824    fn update_followers(
 4825        &self,
 4826        project_only: bool,
 4827        update: proto::update_followers::Variant,
 4828        _: &mut Window,
 4829        cx: &mut App,
 4830    ) -> Option<()> {
 4831        // If this update only applies to for followers in the current project,
 4832        // then skip it unless this project is shared. If it applies to all
 4833        // followers, regardless of project, then set `project_id` to none,
 4834        // indicating that it goes to all followers.
 4835        let project_id = if project_only {
 4836            Some(self.project.read(cx).remote_id()?)
 4837        } else {
 4838            None
 4839        };
 4840        self.app_state().workspace_store.update(cx, |store, cx| {
 4841            store.update_followers(project_id, update, cx)
 4842        })
 4843    }
 4844
 4845    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 4846        self.follower_states.iter().find_map(|(leader_id, state)| {
 4847            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 4848                Some(*leader_id)
 4849            } else {
 4850                None
 4851            }
 4852        })
 4853    }
 4854
 4855    fn leader_updated(
 4856        &mut self,
 4857        leader_id: impl Into<CollaboratorId>,
 4858        window: &mut Window,
 4859        cx: &mut Context<Self>,
 4860    ) -> Option<Box<dyn ItemHandle>> {
 4861        cx.notify();
 4862
 4863        let leader_id = leader_id.into();
 4864        let (panel_id, item) = match leader_id {
 4865            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 4866            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 4867        };
 4868
 4869        let state = self.follower_states.get(&leader_id)?;
 4870        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 4871        let pane;
 4872        if let Some(panel_id) = panel_id {
 4873            pane = self
 4874                .activate_panel_for_proto_id(panel_id, window, cx)?
 4875                .pane(cx)?;
 4876            let state = self.follower_states.get_mut(&leader_id)?;
 4877            state.dock_pane = Some(pane.clone());
 4878        } else {
 4879            pane = state.center_pane.clone();
 4880            let state = self.follower_states.get_mut(&leader_id)?;
 4881            if let Some(dock_pane) = state.dock_pane.take() {
 4882                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 4883            }
 4884        }
 4885
 4886        pane.update(cx, |pane, cx| {
 4887            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 4888            if let Some(index) = pane.index_for_item(item.as_ref()) {
 4889                pane.activate_item(index, false, false, window, cx);
 4890            } else {
 4891                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 4892            }
 4893
 4894            if focus_active_item {
 4895                pane.focus_active_item(window, cx)
 4896            }
 4897        });
 4898
 4899        Some(item)
 4900    }
 4901
 4902    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 4903        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 4904        let active_view_id = state.active_view_id?;
 4905        Some(
 4906            state
 4907                .items_by_leader_view_id
 4908                .get(&active_view_id)?
 4909                .view
 4910                .boxed_clone(),
 4911        )
 4912    }
 4913
 4914    fn active_item_for_peer(
 4915        &self,
 4916        peer_id: PeerId,
 4917        window: &mut Window,
 4918        cx: &mut Context<Self>,
 4919    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 4920        let call = self.active_call()?;
 4921        let room = call.read(cx).room()?.read(cx);
 4922        let participant = room.remote_participant_for_peer_id(peer_id)?;
 4923        let leader_in_this_app;
 4924        let leader_in_this_project;
 4925        match participant.location {
 4926            call::ParticipantLocation::SharedProject { project_id } => {
 4927                leader_in_this_app = true;
 4928                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 4929            }
 4930            call::ParticipantLocation::UnsharedProject => {
 4931                leader_in_this_app = true;
 4932                leader_in_this_project = false;
 4933            }
 4934            call::ParticipantLocation::External => {
 4935                leader_in_this_app = false;
 4936                leader_in_this_project = false;
 4937            }
 4938        };
 4939        let state = self.follower_states.get(&peer_id.into())?;
 4940        let mut item_to_activate = None;
 4941        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 4942            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 4943                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 4944            {
 4945                item_to_activate = Some((item.location, item.view.boxed_clone()));
 4946            }
 4947        } else if let Some(shared_screen) =
 4948            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 4949        {
 4950            item_to_activate = Some((None, Box::new(shared_screen)));
 4951        }
 4952        item_to_activate
 4953    }
 4954
 4955    fn shared_screen_for_peer(
 4956        &self,
 4957        peer_id: PeerId,
 4958        pane: &Entity<Pane>,
 4959        window: &mut Window,
 4960        cx: &mut App,
 4961    ) -> Option<Entity<SharedScreen>> {
 4962        let call = self.active_call()?;
 4963        let room = call.read(cx).room()?.clone();
 4964        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 4965        let track = participant.video_tracks.values().next()?.clone();
 4966        let user = participant.user.clone();
 4967
 4968        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 4969            if item.read(cx).peer_id == peer_id {
 4970                return Some(item);
 4971            }
 4972        }
 4973
 4974        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 4975    }
 4976
 4977    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4978        if window.is_window_active() {
 4979            self.update_active_view_for_followers(window, cx);
 4980
 4981            if let Some(database_id) = self.database_id {
 4982                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 4983                    .detach();
 4984            }
 4985        } else {
 4986            for pane in &self.panes {
 4987                pane.update(cx, |pane, cx| {
 4988                    if let Some(item) = pane.active_item() {
 4989                        item.workspace_deactivated(window, cx);
 4990                    }
 4991                    for item in pane.items() {
 4992                        if matches!(
 4993                            item.workspace_settings(cx).autosave,
 4994                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 4995                        ) {
 4996                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 4997                                .detach_and_log_err(cx);
 4998                        }
 4999                    }
 5000                });
 5001            }
 5002        }
 5003    }
 5004
 5005    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5006        self.active_call.as_ref().map(|(call, _)| call)
 5007    }
 5008
 5009    fn on_active_call_event(
 5010        &mut self,
 5011        _: &Entity<ActiveCall>,
 5012        event: &call::room::Event,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) {
 5016        match event {
 5017            call::room::Event::ParticipantLocationChanged { participant_id }
 5018            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5019                self.leader_updated(participant_id, window, cx);
 5020            }
 5021            _ => {}
 5022        }
 5023    }
 5024
 5025    pub fn database_id(&self) -> Option<WorkspaceId> {
 5026        self.database_id
 5027    }
 5028
 5029    pub fn session_id(&self) -> Option<String> {
 5030        self.session_id.clone()
 5031    }
 5032
 5033    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5034        let project = self.project().read(cx);
 5035        project
 5036            .visible_worktrees(cx)
 5037            .map(|worktree| worktree.read(cx).abs_path())
 5038            .collect::<Vec<_>>()
 5039    }
 5040
 5041    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5042        match member {
 5043            Member::Axis(PaneAxis { members, .. }) => {
 5044                for child in members.iter() {
 5045                    self.remove_panes(child.clone(), window, cx)
 5046                }
 5047            }
 5048            Member::Pane(pane) => {
 5049                self.force_remove_pane(&pane, &None, window, cx);
 5050            }
 5051        }
 5052    }
 5053
 5054    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5055        self.session_id.take();
 5056        self.serialize_workspace_internal(window, cx)
 5057    }
 5058
 5059    fn force_remove_pane(
 5060        &mut self,
 5061        pane: &Entity<Pane>,
 5062        focus_on: &Option<Entity<Pane>>,
 5063        window: &mut Window,
 5064        cx: &mut Context<Workspace>,
 5065    ) {
 5066        self.panes.retain(|p| p != pane);
 5067        if let Some(focus_on) = focus_on {
 5068            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5069        } else if self.active_pane() == pane {
 5070            self.panes
 5071                .last()
 5072                .unwrap()
 5073                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5074        }
 5075        if self.last_active_center_pane == Some(pane.downgrade()) {
 5076            self.last_active_center_pane = None;
 5077        }
 5078        cx.notify();
 5079    }
 5080
 5081    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5082        if self._schedule_serialize_workspace.is_none() {
 5083            self._schedule_serialize_workspace =
 5084                Some(cx.spawn_in(window, async move |this, cx| {
 5085                    cx.background_executor()
 5086                        .timer(SERIALIZATION_THROTTLE_TIME)
 5087                        .await;
 5088                    this.update_in(cx, |this, window, cx| {
 5089                        this.serialize_workspace_internal(window, cx).detach();
 5090                        this._schedule_serialize_workspace.take();
 5091                    })
 5092                    .log_err();
 5093                }));
 5094        }
 5095    }
 5096
 5097    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5098        let Some(database_id) = self.database_id() else {
 5099            return Task::ready(());
 5100        };
 5101
 5102        fn serialize_pane_handle(
 5103            pane_handle: &Entity<Pane>,
 5104            window: &mut Window,
 5105            cx: &mut App,
 5106        ) -> SerializedPane {
 5107            let (items, active, pinned_count) = {
 5108                let pane = pane_handle.read(cx);
 5109                let active_item_id = pane.active_item().map(|item| item.item_id());
 5110                (
 5111                    pane.items()
 5112                        .filter_map(|handle| {
 5113                            let handle = handle.to_serializable_item_handle(cx)?;
 5114
 5115                            Some(SerializedItem {
 5116                                kind: Arc::from(handle.serialized_item_kind()),
 5117                                item_id: handle.item_id().as_u64(),
 5118                                active: Some(handle.item_id()) == active_item_id,
 5119                                preview: pane.is_active_preview_item(handle.item_id()),
 5120                            })
 5121                        })
 5122                        .collect::<Vec<_>>(),
 5123                    pane.has_focus(window, cx),
 5124                    pane.pinned_count(),
 5125                )
 5126            };
 5127
 5128            SerializedPane::new(items, active, pinned_count)
 5129        }
 5130
 5131        fn build_serialized_pane_group(
 5132            pane_group: &Member,
 5133            window: &mut Window,
 5134            cx: &mut App,
 5135        ) -> SerializedPaneGroup {
 5136            match pane_group {
 5137                Member::Axis(PaneAxis {
 5138                    axis,
 5139                    members,
 5140                    flexes,
 5141                    bounding_boxes: _,
 5142                }) => SerializedPaneGroup::Group {
 5143                    axis: SerializedAxis(*axis),
 5144                    children: members
 5145                        .iter()
 5146                        .map(|member| build_serialized_pane_group(member, window, cx))
 5147                        .collect::<Vec<_>>(),
 5148                    flexes: Some(flexes.lock().clone()),
 5149                },
 5150                Member::Pane(pane_handle) => {
 5151                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5152                }
 5153            }
 5154        }
 5155
 5156        fn build_serialized_docks(
 5157            this: &Workspace,
 5158            window: &mut Window,
 5159            cx: &mut App,
 5160        ) -> DockStructure {
 5161            let left_dock = this.left_dock.read(cx);
 5162            let left_visible = left_dock.is_open();
 5163            let left_active_panel = left_dock
 5164                .active_panel()
 5165                .map(|panel| panel.persistent_name().to_string());
 5166            let left_dock_zoom = left_dock
 5167                .active_panel()
 5168                .map(|panel| panel.is_zoomed(window, cx))
 5169                .unwrap_or(false);
 5170
 5171            let right_dock = this.right_dock.read(cx);
 5172            let right_visible = right_dock.is_open();
 5173            let right_active_panel = right_dock
 5174                .active_panel()
 5175                .map(|panel| panel.persistent_name().to_string());
 5176            let right_dock_zoom = right_dock
 5177                .active_panel()
 5178                .map(|panel| panel.is_zoomed(window, cx))
 5179                .unwrap_or(false);
 5180
 5181            let bottom_dock = this.bottom_dock.read(cx);
 5182            let bottom_visible = bottom_dock.is_open();
 5183            let bottom_active_panel = bottom_dock
 5184                .active_panel()
 5185                .map(|panel| panel.persistent_name().to_string());
 5186            let bottom_dock_zoom = bottom_dock
 5187                .active_panel()
 5188                .map(|panel| panel.is_zoomed(window, cx))
 5189                .unwrap_or(false);
 5190
 5191            DockStructure {
 5192                left: DockData {
 5193                    visible: left_visible,
 5194                    active_panel: left_active_panel,
 5195                    zoom: left_dock_zoom,
 5196                },
 5197                right: DockData {
 5198                    visible: right_visible,
 5199                    active_panel: right_active_panel,
 5200                    zoom: right_dock_zoom,
 5201                },
 5202                bottom: DockData {
 5203                    visible: bottom_visible,
 5204                    active_panel: bottom_active_panel,
 5205                    zoom: bottom_dock_zoom,
 5206                },
 5207            }
 5208        }
 5209
 5210        match self.serialize_workspace_location(cx) {
 5211            WorkspaceLocation::Location(location, paths) => {
 5212                let breakpoints = self.project.update(cx, |project, cx| {
 5213                    project
 5214                        .breakpoint_store()
 5215                        .read(cx)
 5216                        .all_source_breakpoints(cx)
 5217                });
 5218
 5219                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5220                let docks = build_serialized_docks(self, window, cx);
 5221                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5222                let serialized_workspace = SerializedWorkspace {
 5223                    id: database_id,
 5224                    location,
 5225                    paths,
 5226                    center_group,
 5227                    window_bounds,
 5228                    display: Default::default(),
 5229                    docks,
 5230                    centered_layout: self.centered_layout,
 5231                    session_id: self.session_id.clone(),
 5232                    breakpoints,
 5233                    window_id: Some(window.window_handle().window_id().as_u64()),
 5234                };
 5235
 5236                window.spawn(cx, async move |_| {
 5237                    persistence::DB.save_workspace(serialized_workspace).await;
 5238                })
 5239            }
 5240            WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
 5241                persistence::DB
 5242                    .set_session_id(database_id, None)
 5243                    .await
 5244                    .log_err();
 5245            }),
 5246            WorkspaceLocation::None => Task::ready(()),
 5247        }
 5248    }
 5249
 5250    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5251        let paths = PathList::new(&self.root_paths(cx));
 5252        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5253            WorkspaceLocation::Location(
 5254                SerializedWorkspaceLocation::Ssh(SerializedSshConnection {
 5255                    host: connection.host,
 5256                    port: connection.port,
 5257                    user: connection.username,
 5258                }),
 5259                paths,
 5260            )
 5261        } else if self.project.read(cx).is_local() {
 5262            if !paths.is_empty() {
 5263                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5264            } else {
 5265                WorkspaceLocation::DetachFromSession
 5266            }
 5267        } else {
 5268            WorkspaceLocation::None
 5269        }
 5270    }
 5271
 5272    fn update_history(&self, cx: &mut App) {
 5273        let Some(id) = self.database_id() else {
 5274            return;
 5275        };
 5276        if !self.project.read(cx).is_local() {
 5277            return;
 5278        }
 5279        if let Some(manager) = HistoryManager::global(cx) {
 5280            let paths = PathList::new(&self.root_paths(cx));
 5281            manager.update(cx, |this, cx| {
 5282                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5283            });
 5284        }
 5285    }
 5286
 5287    async fn serialize_items(
 5288        this: &WeakEntity<Self>,
 5289        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5290        cx: &mut AsyncWindowContext,
 5291    ) -> Result<()> {
 5292        const CHUNK_SIZE: usize = 200;
 5293
 5294        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5295
 5296        while let Some(items_received) = serializable_items.next().await {
 5297            let unique_items =
 5298                items_received
 5299                    .into_iter()
 5300                    .fold(HashMap::default(), |mut acc, item| {
 5301                        acc.entry(item.item_id()).or_insert(item);
 5302                        acc
 5303                    });
 5304
 5305            // We use into_iter() here so that the references to the items are moved into
 5306            // the tasks and not kept alive while we're sleeping.
 5307            for (_, item) in unique_items.into_iter() {
 5308                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5309                    item.serialize(workspace, false, window, cx)
 5310                }) {
 5311                    cx.background_spawn(async move { task.await.log_err() })
 5312                        .detach();
 5313                }
 5314            }
 5315
 5316            cx.background_executor()
 5317                .timer(SERIALIZATION_THROTTLE_TIME)
 5318                .await;
 5319        }
 5320
 5321        Ok(())
 5322    }
 5323
 5324    pub(crate) fn enqueue_item_serialization(
 5325        &mut self,
 5326        item: Box<dyn SerializableItemHandle>,
 5327    ) -> Result<()> {
 5328        self.serializable_items_tx
 5329            .unbounded_send(item)
 5330            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5331    }
 5332
 5333    pub(crate) fn load_workspace(
 5334        serialized_workspace: SerializedWorkspace,
 5335        paths_to_open: Vec<Option<ProjectPath>>,
 5336        window: &mut Window,
 5337        cx: &mut Context<Workspace>,
 5338    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5339        cx.spawn_in(window, async move |workspace, cx| {
 5340            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5341
 5342            let mut center_group = None;
 5343            let mut center_items = None;
 5344
 5345            // Traverse the splits tree and add to things
 5346            if let Some((group, active_pane, items)) = serialized_workspace
 5347                .center_group
 5348                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5349                .await
 5350            {
 5351                center_items = Some(items);
 5352                center_group = Some((group, active_pane))
 5353            }
 5354
 5355            let mut items_by_project_path = HashMap::default();
 5356            let mut item_ids_by_kind = HashMap::default();
 5357            let mut all_deserialized_items = Vec::default();
 5358            cx.update(|_, cx| {
 5359                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5360                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5361                        item_ids_by_kind
 5362                            .entry(serializable_item_handle.serialized_item_kind())
 5363                            .or_insert(Vec::new())
 5364                            .push(item.item_id().as_u64() as ItemId);
 5365                    }
 5366
 5367                    if let Some(project_path) = item.project_path(cx) {
 5368                        items_by_project_path.insert(project_path, item.clone());
 5369                    }
 5370                    all_deserialized_items.push(item);
 5371                }
 5372            })?;
 5373
 5374            let opened_items = paths_to_open
 5375                .into_iter()
 5376                .map(|path_to_open| {
 5377                    path_to_open
 5378                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5379                })
 5380                .collect::<Vec<_>>();
 5381
 5382            // Remove old panes from workspace panes list
 5383            workspace.update_in(cx, |workspace, window, cx| {
 5384                if let Some((center_group, active_pane)) = center_group {
 5385                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5386
 5387                    // Swap workspace center group
 5388                    workspace.center = PaneGroup::with_root(center_group);
 5389                    if let Some(active_pane) = active_pane {
 5390                        workspace.set_active_pane(&active_pane, window, cx);
 5391                        cx.focus_self(window);
 5392                    } else {
 5393                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5394                    }
 5395                }
 5396
 5397                let docks = serialized_workspace.docks;
 5398
 5399                for (dock, serialized_dock) in [
 5400                    (&mut workspace.right_dock, docks.right),
 5401                    (&mut workspace.left_dock, docks.left),
 5402                    (&mut workspace.bottom_dock, docks.bottom),
 5403                ]
 5404                .iter_mut()
 5405                {
 5406                    dock.update(cx, |dock, cx| {
 5407                        dock.serialized_dock = Some(serialized_dock.clone());
 5408                        dock.restore_state(window, cx);
 5409                    });
 5410                }
 5411
 5412                cx.notify();
 5413            })?;
 5414
 5415            let _ = project
 5416                .update(cx, |project, cx| {
 5417                    project
 5418                        .breakpoint_store()
 5419                        .update(cx, |breakpoint_store, cx| {
 5420                            breakpoint_store
 5421                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5422                        })
 5423                })?
 5424                .await;
 5425
 5426            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5427            // after loading the items, we might have different items and in order to avoid
 5428            // the database filling up, we delete items that haven't been loaded now.
 5429            //
 5430            // The items that have been loaded, have been saved after they've been added to the workspace.
 5431            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5432                item_ids_by_kind
 5433                    .into_iter()
 5434                    .map(|(item_kind, loaded_items)| {
 5435                        SerializableItemRegistry::cleanup(
 5436                            item_kind,
 5437                            serialized_workspace.id,
 5438                            loaded_items,
 5439                            window,
 5440                            cx,
 5441                        )
 5442                        .log_err()
 5443                    })
 5444                    .collect::<Vec<_>>()
 5445            })?;
 5446
 5447            futures::future::join_all(clean_up_tasks).await;
 5448
 5449            workspace
 5450                .update_in(cx, |workspace, window, cx| {
 5451                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5452                    workspace.serialize_workspace_internal(window, cx).detach();
 5453
 5454                    // Ensure that we mark the window as edited if we did load dirty items
 5455                    workspace.update_window_edited(window, cx);
 5456                })
 5457                .ok();
 5458
 5459            Ok(opened_items)
 5460        })
 5461    }
 5462
 5463    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5464        self.add_workspace_actions_listeners(div, window, cx)
 5465            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5466            .on_action(cx.listener(Self::close_all_items_and_panes))
 5467            .on_action(cx.listener(Self::save_all))
 5468            .on_action(cx.listener(Self::send_keystrokes))
 5469            .on_action(cx.listener(Self::add_folder_to_project))
 5470            .on_action(cx.listener(Self::follow_next_collaborator))
 5471            .on_action(cx.listener(Self::close_window))
 5472            .on_action(cx.listener(Self::activate_pane_at_index))
 5473            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5474            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5475            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 5476            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5477                let pane = workspace.active_pane().clone();
 5478                workspace.unfollow_in_pane(&pane, window, cx);
 5479            }))
 5480            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5481                workspace
 5482                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5483                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5484            }))
 5485            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5486                workspace
 5487                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5488                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5489            }))
 5490            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5491                workspace
 5492                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5493                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5494            }))
 5495            .on_action(
 5496                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5497                    workspace.activate_previous_pane(window, cx)
 5498                }),
 5499            )
 5500            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5501                workspace.activate_next_pane(window, cx)
 5502            }))
 5503            .on_action(
 5504                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5505                    workspace.activate_next_window(cx)
 5506                }),
 5507            )
 5508            .on_action(
 5509                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5510                    workspace.activate_previous_window(cx)
 5511                }),
 5512            )
 5513            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5514                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5515            }))
 5516            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5517                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5518            }))
 5519            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5520                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5521            }))
 5522            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 5523                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 5524            }))
 5525            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5526                workspace.activate_next_pane(window, cx)
 5527            }))
 5528            .on_action(cx.listener(
 5529                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 5530                    workspace.move_item_to_pane_in_direction(action, window, cx)
 5531                },
 5532            ))
 5533            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 5534                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 5535            }))
 5536            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 5537                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 5538            }))
 5539            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 5540                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 5541            }))
 5542            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 5543                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 5544            }))
 5545            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 5546                this.toggle_dock(DockPosition::Left, window, cx);
 5547            }))
 5548            .on_action(cx.listener(
 5549                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 5550                    workspace.toggle_dock(DockPosition::Right, window, cx);
 5551                },
 5552            ))
 5553            .on_action(cx.listener(
 5554                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 5555                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 5556                },
 5557            ))
 5558            .on_action(cx.listener(
 5559                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 5560                    if !workspace.close_active_dock(window, cx) {
 5561                        cx.propagate();
 5562                    }
 5563                },
 5564            ))
 5565            .on_action(
 5566                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 5567                    workspace.close_all_docks(window, cx);
 5568                }),
 5569            )
 5570            .on_action(cx.listener(
 5571                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 5572                    workspace.clear_all_notifications(cx);
 5573                },
 5574            ))
 5575            .on_action(cx.listener(
 5576                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 5577                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 5578                        workspace.suppress_notification(&notification_id, cx);
 5579                    }
 5580                },
 5581            ))
 5582            .on_action(cx.listener(
 5583                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 5584                    workspace.reopen_closed_item(window, cx).detach();
 5585                },
 5586            ))
 5587            .on_action(cx.listener(
 5588                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 5589                    for dock in workspace.all_docks() {
 5590                        if dock.focus_handle(cx).contains_focused(window, cx) {
 5591                            let Some(panel) = dock.read(cx).active_panel() else {
 5592                                return;
 5593                            };
 5594
 5595                            // Set to `None`, then the size will fall back to the default.
 5596                            panel.clone().set_size(None, window, cx);
 5597
 5598                            return;
 5599                        }
 5600                    }
 5601                },
 5602            ))
 5603            .on_action(cx.listener(
 5604                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 5605                    for dock in workspace.all_docks() {
 5606                        if let Some(panel) = dock.read(cx).visible_panel() {
 5607                            // Set to `None`, then the size will fall back to the default.
 5608                            panel.clone().set_size(None, window, cx);
 5609                        }
 5610                    }
 5611                },
 5612            ))
 5613            .on_action(cx.listener(
 5614                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 5615                    adjust_active_dock_size_by_px(
 5616                        px_with_ui_font_fallback(act.px, cx),
 5617                        workspace,
 5618                        window,
 5619                        cx,
 5620                    );
 5621                },
 5622            ))
 5623            .on_action(cx.listener(
 5624                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 5625                    adjust_active_dock_size_by_px(
 5626                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5627                        workspace,
 5628                        window,
 5629                        cx,
 5630                    );
 5631                },
 5632            ))
 5633            .on_action(cx.listener(
 5634                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 5635                    adjust_open_docks_size_by_px(
 5636                        px_with_ui_font_fallback(act.px, cx),
 5637                        workspace,
 5638                        window,
 5639                        cx,
 5640                    );
 5641                },
 5642            ))
 5643            .on_action(cx.listener(
 5644                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 5645                    adjust_open_docks_size_by_px(
 5646                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5647                        workspace,
 5648                        window,
 5649                        cx,
 5650                    );
 5651                },
 5652            ))
 5653            .on_action(cx.listener(Workspace::toggle_centered_layout))
 5654            .on_action(cx.listener(Workspace::cancel))
 5655    }
 5656
 5657    #[cfg(any(test, feature = "test-support"))]
 5658    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 5659        use node_runtime::NodeRuntime;
 5660        use session::Session;
 5661
 5662        let client = project.read(cx).client();
 5663        let user_store = project.read(cx).user_store();
 5664        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 5665        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 5666        window.activate_window();
 5667        let app_state = Arc::new(AppState {
 5668            languages: project.read(cx).languages().clone(),
 5669            workspace_store,
 5670            client,
 5671            user_store,
 5672            fs: project.read(cx).fs().clone(),
 5673            build_window_options: |_, _| Default::default(),
 5674            node_runtime: NodeRuntime::unavailable(),
 5675            session,
 5676        });
 5677        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 5678        workspace
 5679            .active_pane
 5680            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5681        workspace
 5682    }
 5683
 5684    pub fn register_action<A: Action>(
 5685        &mut self,
 5686        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 5687    ) -> &mut Self {
 5688        let callback = Arc::new(callback);
 5689
 5690        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 5691            let callback = callback.clone();
 5692            div.on_action(cx.listener(move |workspace, event, window, cx| {
 5693                (callback)(workspace, event, window, cx)
 5694            }))
 5695        }));
 5696        self
 5697    }
 5698    pub fn register_action_renderer(
 5699        &mut self,
 5700        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 5701    ) -> &mut Self {
 5702        self.workspace_actions.push(Box::new(callback));
 5703        self
 5704    }
 5705
 5706    fn add_workspace_actions_listeners(
 5707        &self,
 5708        mut div: Div,
 5709        window: &mut Window,
 5710        cx: &mut Context<Self>,
 5711    ) -> Div {
 5712        for action in self.workspace_actions.iter() {
 5713            div = (action)(div, self, window, cx)
 5714        }
 5715        div
 5716    }
 5717
 5718    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 5719        self.modal_layer.read(cx).has_active_modal()
 5720    }
 5721
 5722    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 5723        self.modal_layer.read(cx).active_modal()
 5724    }
 5725
 5726    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 5727    where
 5728        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 5729    {
 5730        self.modal_layer.update(cx, |modal_layer, cx| {
 5731            modal_layer.toggle_modal(window, cx, build)
 5732        })
 5733    }
 5734
 5735    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 5736        self.toast_layer
 5737            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 5738    }
 5739
 5740    pub fn toggle_centered_layout(
 5741        &mut self,
 5742        _: &ToggleCenteredLayout,
 5743        _: &mut Window,
 5744        cx: &mut Context<Self>,
 5745    ) {
 5746        self.centered_layout = !self.centered_layout;
 5747        if let Some(database_id) = self.database_id() {
 5748            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 5749                .detach_and_log_err(cx);
 5750        }
 5751        cx.notify();
 5752    }
 5753
 5754    fn adjust_padding(padding: Option<f32>) -> f32 {
 5755        padding
 5756            .unwrap_or(Self::DEFAULT_PADDING)
 5757            .clamp(0.0, Self::MAX_PADDING)
 5758    }
 5759
 5760    fn render_dock(
 5761        &self,
 5762        position: DockPosition,
 5763        dock: &Entity<Dock>,
 5764        window: &mut Window,
 5765        cx: &mut App,
 5766    ) -> Option<Div> {
 5767        if self.zoomed_position == Some(position) {
 5768            return None;
 5769        }
 5770
 5771        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 5772            let pane = panel.pane(cx)?;
 5773            let follower_states = &self.follower_states;
 5774            leader_border_for_pane(follower_states, &pane, window, cx)
 5775        });
 5776
 5777        Some(
 5778            div()
 5779                .flex()
 5780                .flex_none()
 5781                .overflow_hidden()
 5782                .child(dock.clone())
 5783                .children(leader_border),
 5784        )
 5785    }
 5786
 5787    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 5788        window.root().flatten()
 5789    }
 5790
 5791    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 5792        self.zoomed.as_ref()
 5793    }
 5794
 5795    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 5796        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 5797            return;
 5798        };
 5799        let windows = cx.windows();
 5800        let Some(next_window) = windows
 5801            .iter()
 5802            .cycle()
 5803            .skip_while(|window| window.window_id() != current_window_id)
 5804            .nth(1)
 5805        else {
 5806            return;
 5807        };
 5808        next_window
 5809            .update(cx, |_, window, _| window.activate_window())
 5810            .ok();
 5811    }
 5812
 5813    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 5814        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 5815            return;
 5816        };
 5817        let windows = cx.windows();
 5818        let Some(prev_window) = windows
 5819            .iter()
 5820            .rev()
 5821            .cycle()
 5822            .skip_while(|window| window.window_id() != current_window_id)
 5823            .nth(1)
 5824        else {
 5825            return;
 5826        };
 5827        prev_window
 5828            .update(cx, |_, window, _| window.activate_window())
 5829            .ok();
 5830    }
 5831
 5832    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 5833        if cx.stop_active_drag(window) {
 5834        } else if let Some((notification_id, _)) = self.notifications.pop() {
 5835            dismiss_app_notification(&notification_id, cx);
 5836        } else {
 5837            cx.propagate();
 5838        }
 5839    }
 5840
 5841    fn adjust_dock_size_by_px(
 5842        &mut self,
 5843        panel_size: Pixels,
 5844        dock_pos: DockPosition,
 5845        px: Pixels,
 5846        window: &mut Window,
 5847        cx: &mut Context<Self>,
 5848    ) {
 5849        match dock_pos {
 5850            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 5851            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 5852            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 5853        }
 5854    }
 5855
 5856    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5857        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 5858
 5859        self.left_dock.update(cx, |left_dock, cx| {
 5860            if WorkspaceSettings::get_global(cx)
 5861                .resize_all_panels_in_dock
 5862                .contains(&DockPosition::Left)
 5863            {
 5864                left_dock.resize_all_panels(Some(size), window, cx);
 5865            } else {
 5866                left_dock.resize_active_panel(Some(size), window, cx);
 5867            }
 5868        });
 5869    }
 5870
 5871    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5872        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 5873        self.left_dock.read_with(cx, |left_dock, cx| {
 5874            let left_dock_size = left_dock
 5875                .active_panel_size(window, cx)
 5876                .unwrap_or(Pixels(0.0));
 5877            if left_dock_size + size > self.bounds.right() {
 5878                size = self.bounds.right() - left_dock_size
 5879            }
 5880        });
 5881        self.right_dock.update(cx, |right_dock, cx| {
 5882            if WorkspaceSettings::get_global(cx)
 5883                .resize_all_panels_in_dock
 5884                .contains(&DockPosition::Right)
 5885            {
 5886                right_dock.resize_all_panels(Some(size), window, cx);
 5887            } else {
 5888                right_dock.resize_active_panel(Some(size), window, cx);
 5889            }
 5890        });
 5891    }
 5892
 5893    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 5894        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 5895        self.bottom_dock.update(cx, |bottom_dock, cx| {
 5896            if WorkspaceSettings::get_global(cx)
 5897                .resize_all_panels_in_dock
 5898                .contains(&DockPosition::Bottom)
 5899            {
 5900                bottom_dock.resize_all_panels(Some(size), window, cx);
 5901            } else {
 5902                bottom_dock.resize_active_panel(Some(size), window, cx);
 5903            }
 5904        });
 5905    }
 5906
 5907    fn toggle_edit_predictions_all_files(
 5908        &mut self,
 5909        _: &ToggleEditPrediction,
 5910        _window: &mut Window,
 5911        cx: &mut Context<Self>,
 5912    ) {
 5913        let fs = self.project().read(cx).fs().clone();
 5914        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 5915        update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
 5916            file.defaults.show_edit_predictions = Some(!show_edit_predictions)
 5917        });
 5918    }
 5919}
 5920
 5921fn leader_border_for_pane(
 5922    follower_states: &HashMap<CollaboratorId, FollowerState>,
 5923    pane: &Entity<Pane>,
 5924    _: &Window,
 5925    cx: &App,
 5926) -> Option<Div> {
 5927    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 5928        if state.pane() == pane {
 5929            Some((*leader_id, state))
 5930        } else {
 5931            None
 5932        }
 5933    })?;
 5934
 5935    let mut leader_color = match leader_id {
 5936        CollaboratorId::PeerId(leader_peer_id) => {
 5937            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 5938            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 5939
 5940            cx.theme()
 5941                .players()
 5942                .color_for_participant(leader.participant_index.0)
 5943                .cursor
 5944        }
 5945        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 5946    };
 5947    leader_color.fade_out(0.3);
 5948    Some(
 5949        div()
 5950            .absolute()
 5951            .size_full()
 5952            .left_0()
 5953            .top_0()
 5954            .border_2()
 5955            .border_color(leader_color),
 5956    )
 5957}
 5958
 5959fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 5960    ZED_WINDOW_POSITION
 5961        .zip(*ZED_WINDOW_SIZE)
 5962        .map(|(position, size)| Bounds {
 5963            origin: position,
 5964            size,
 5965        })
 5966}
 5967
 5968fn open_items(
 5969    serialized_workspace: Option<SerializedWorkspace>,
 5970    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 5971    window: &mut Window,
 5972    cx: &mut Context<Workspace>,
 5973) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 5974    let restored_items = serialized_workspace.map(|serialized_workspace| {
 5975        Workspace::load_workspace(
 5976            serialized_workspace,
 5977            project_paths_to_open
 5978                .iter()
 5979                .map(|(_, project_path)| project_path)
 5980                .cloned()
 5981                .collect(),
 5982            window,
 5983            cx,
 5984        )
 5985    });
 5986
 5987    cx.spawn_in(window, async move |workspace, cx| {
 5988        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 5989
 5990        if let Some(restored_items) = restored_items {
 5991            let restored_items = restored_items.await?;
 5992
 5993            let restored_project_paths = restored_items
 5994                .iter()
 5995                .filter_map(|item| {
 5996                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 5997                        .ok()
 5998                        .flatten()
 5999                })
 6000                .collect::<HashSet<_>>();
 6001
 6002            for restored_item in restored_items {
 6003                opened_items.push(restored_item.map(Ok));
 6004            }
 6005
 6006            project_paths_to_open
 6007                .iter_mut()
 6008                .for_each(|(_, project_path)| {
 6009                    if let Some(project_path_to_open) = project_path
 6010                        && restored_project_paths.contains(project_path_to_open)
 6011                    {
 6012                        *project_path = None;
 6013                    }
 6014                });
 6015        } else {
 6016            for _ in 0..project_paths_to_open.len() {
 6017                opened_items.push(None);
 6018            }
 6019        }
 6020        assert!(opened_items.len() == project_paths_to_open.len());
 6021
 6022        let tasks =
 6023            project_paths_to_open
 6024                .into_iter()
 6025                .enumerate()
 6026                .map(|(ix, (abs_path, project_path))| {
 6027                    let workspace = workspace.clone();
 6028                    cx.spawn(async move |cx| {
 6029                        let file_project_path = project_path?;
 6030                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6031                            workspace.project().update(cx, |project, cx| {
 6032                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6033                            })
 6034                        });
 6035
 6036                        // We only want to open file paths here. If one of the items
 6037                        // here is a directory, it was already opened further above
 6038                        // with a `find_or_create_worktree`.
 6039                        if let Ok(task) = abs_path_task
 6040                            && task.await.is_none_or(|p| p.is_file())
 6041                        {
 6042                            return Some((
 6043                                ix,
 6044                                workspace
 6045                                    .update_in(cx, |workspace, window, cx| {
 6046                                        workspace.open_path(
 6047                                            file_project_path,
 6048                                            None,
 6049                                            true,
 6050                                            window,
 6051                                            cx,
 6052                                        )
 6053                                    })
 6054                                    .log_err()?
 6055                                    .await,
 6056                            ));
 6057                        }
 6058                        None
 6059                    })
 6060                });
 6061
 6062        let tasks = tasks.collect::<Vec<_>>();
 6063
 6064        let tasks = futures::future::join_all(tasks);
 6065        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6066            opened_items[ix] = Some(path_open_result);
 6067        }
 6068
 6069        Ok(opened_items)
 6070    })
 6071}
 6072
 6073enum ActivateInDirectionTarget {
 6074    Pane(Entity<Pane>),
 6075    Dock(Entity<Dock>),
 6076}
 6077
 6078fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6079    workspace
 6080        .update(cx, |workspace, _, cx| {
 6081            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6082                struct DatabaseFailedNotification;
 6083
 6084                workspace.show_notification(
 6085                    NotificationId::unique::<DatabaseFailedNotification>(),
 6086                    cx,
 6087                    |cx| {
 6088                        cx.new(|cx| {
 6089                            MessageNotification::new("Failed to load the database file.", cx)
 6090                                .primary_message("File an Issue")
 6091                                .primary_icon(IconName::Plus)
 6092                                .primary_on_click(|window, cx| {
 6093                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6094                                })
 6095                        })
 6096                    },
 6097                );
 6098            }
 6099        })
 6100        .log_err();
 6101}
 6102
 6103fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6104    if val == 0 {
 6105        ThemeSettings::get_global(cx).ui_font_size(cx)
 6106    } else {
 6107        px(val as f32)
 6108    }
 6109}
 6110
 6111fn adjust_active_dock_size_by_px(
 6112    px: Pixels,
 6113    workspace: &mut Workspace,
 6114    window: &mut Window,
 6115    cx: &mut Context<Workspace>,
 6116) {
 6117    let Some(active_dock) = workspace
 6118        .all_docks()
 6119        .into_iter()
 6120        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6121    else {
 6122        return;
 6123    };
 6124    let dock = active_dock.read(cx);
 6125    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6126        return;
 6127    };
 6128    let dock_pos = dock.position();
 6129    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6130}
 6131
 6132fn adjust_open_docks_size_by_px(
 6133    px: Pixels,
 6134    workspace: &mut Workspace,
 6135    window: &mut Window,
 6136    cx: &mut Context<Workspace>,
 6137) {
 6138    let docks = workspace
 6139        .all_docks()
 6140        .into_iter()
 6141        .filter_map(|dock| {
 6142            if dock.read(cx).is_open() {
 6143                let dock = dock.read(cx);
 6144                let panel_size = dock.active_panel_size(window, cx)?;
 6145                let dock_pos = dock.position();
 6146                Some((panel_size, dock_pos, px))
 6147            } else {
 6148                None
 6149            }
 6150        })
 6151        .collect::<Vec<_>>();
 6152
 6153    docks
 6154        .into_iter()
 6155        .for_each(|(panel_size, dock_pos, offset)| {
 6156            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6157        });
 6158}
 6159
 6160impl Focusable for Workspace {
 6161    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6162        self.active_pane.focus_handle(cx)
 6163    }
 6164}
 6165
 6166#[derive(Clone)]
 6167struct DraggedDock(DockPosition);
 6168
 6169impl Render for DraggedDock {
 6170    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6171        gpui::Empty
 6172    }
 6173}
 6174
 6175impl Render for Workspace {
 6176    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6177        let mut context = KeyContext::new_with_defaults();
 6178        context.add("Workspace");
 6179        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6180        if let Some(status) = self
 6181            .debugger_provider
 6182            .as_ref()
 6183            .and_then(|provider| provider.active_thread_state(cx))
 6184        {
 6185            match status {
 6186                ThreadStatus::Running | ThreadStatus::Stepping => {
 6187                    context.add("debugger_running");
 6188                }
 6189                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6190                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6191            }
 6192        }
 6193
 6194        let centered_layout = self.centered_layout
 6195            && self.center.panes().len() == 1
 6196            && self.active_item(cx).is_some();
 6197        let render_padding = |size| {
 6198            (size > 0.0).then(|| {
 6199                div()
 6200                    .h_full()
 6201                    .w(relative(size))
 6202                    .bg(cx.theme().colors().editor_background)
 6203                    .border_color(cx.theme().colors().pane_group_border)
 6204            })
 6205        };
 6206        let paddings = if centered_layout {
 6207            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6208            (
 6209                render_padding(Self::adjust_padding(settings.left_padding)),
 6210                render_padding(Self::adjust_padding(settings.right_padding)),
 6211            )
 6212        } else {
 6213            (None, None)
 6214        };
 6215        let ui_font = theme::setup_ui_font(window, cx);
 6216
 6217        let theme = cx.theme().clone();
 6218        let colors = theme.colors();
 6219        let notification_entities = self
 6220            .notifications
 6221            .iter()
 6222            .map(|(_, notification)| notification.entity_id())
 6223            .collect::<Vec<_>>();
 6224        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6225
 6226        client_side_decorations(
 6227            self.actions(div(), window, cx)
 6228                .key_context(context)
 6229                .relative()
 6230                .size_full()
 6231                .flex()
 6232                .flex_col()
 6233                .font(ui_font)
 6234                .gap_0()
 6235                .justify_start()
 6236                .items_start()
 6237                .text_color(colors.text)
 6238                .overflow_hidden()
 6239                .children(self.titlebar_item.clone())
 6240                .on_modifiers_changed(move |_, _, cx| {
 6241                    for &id in &notification_entities {
 6242                        cx.notify(id);
 6243                    }
 6244                })
 6245                .child(
 6246                    div()
 6247                        .size_full()
 6248                        .relative()
 6249                        .flex_1()
 6250                        .flex()
 6251                        .flex_col()
 6252                        .child(
 6253                            div()
 6254                                .id("workspace")
 6255                                .bg(colors.background)
 6256                                .relative()
 6257                                .flex_1()
 6258                                .w_full()
 6259                                .flex()
 6260                                .flex_col()
 6261                                .overflow_hidden()
 6262                                .border_t_1()
 6263                                .border_b_1()
 6264                                .border_color(colors.border)
 6265                                .child({
 6266                                    let this = cx.entity();
 6267                                    canvas(
 6268                                        move |bounds, window, cx| {
 6269                                            this.update(cx, |this, cx| {
 6270                                                let bounds_changed = this.bounds != bounds;
 6271                                                this.bounds = bounds;
 6272
 6273                                                if bounds_changed {
 6274                                                    this.left_dock.update(cx, |dock, cx| {
 6275                                                        dock.clamp_panel_size(
 6276                                                            bounds.size.width,
 6277                                                            window,
 6278                                                            cx,
 6279                                                        )
 6280                                                    });
 6281
 6282                                                    this.right_dock.update(cx, |dock, cx| {
 6283                                                        dock.clamp_panel_size(
 6284                                                            bounds.size.width,
 6285                                                            window,
 6286                                                            cx,
 6287                                                        )
 6288                                                    });
 6289
 6290                                                    this.bottom_dock.update(cx, |dock, cx| {
 6291                                                        dock.clamp_panel_size(
 6292                                                            bounds.size.height,
 6293                                                            window,
 6294                                                            cx,
 6295                                                        )
 6296                                                    });
 6297                                                }
 6298                                            })
 6299                                        },
 6300                                        |_, _, _, _| {},
 6301                                    )
 6302                                    .absolute()
 6303                                    .size_full()
 6304                                })
 6305                                .when(self.zoomed.is_none(), |this| {
 6306                                    this.on_drag_move(cx.listener(
 6307                                        move |workspace,
 6308                                              e: &DragMoveEvent<DraggedDock>,
 6309                                              window,
 6310                                              cx| {
 6311                                            if workspace.previous_dock_drag_coordinates
 6312                                                != Some(e.event.position)
 6313                                            {
 6314                                                workspace.previous_dock_drag_coordinates =
 6315                                                    Some(e.event.position);
 6316                                                match e.drag(cx).0 {
 6317                                                    DockPosition::Left => {
 6318                                                        workspace.resize_left_dock(
 6319                                                            e.event.position.x
 6320                                                                - workspace.bounds.left(),
 6321                                                            window,
 6322                                                            cx,
 6323                                                        );
 6324                                                    }
 6325                                                    DockPosition::Right => {
 6326                                                        workspace.resize_right_dock(
 6327                                                            workspace.bounds.right()
 6328                                                                - e.event.position.x,
 6329                                                            window,
 6330                                                            cx,
 6331                                                        );
 6332                                                    }
 6333                                                    DockPosition::Bottom => {
 6334                                                        workspace.resize_bottom_dock(
 6335                                                            workspace.bounds.bottom()
 6336                                                                - e.event.position.y,
 6337                                                            window,
 6338                                                            cx,
 6339                                                        );
 6340                                                    }
 6341                                                };
 6342                                                workspace.serialize_workspace(window, cx);
 6343                                            }
 6344                                        },
 6345                                    ))
 6346                                })
 6347                                .child({
 6348                                    match bottom_dock_layout {
 6349                                        BottomDockLayout::Full => div()
 6350                                            .flex()
 6351                                            .flex_col()
 6352                                            .h_full()
 6353                                            .child(
 6354                                                div()
 6355                                                    .flex()
 6356                                                    .flex_row()
 6357                                                    .flex_1()
 6358                                                    .overflow_hidden()
 6359                                                    .children(self.render_dock(
 6360                                                        DockPosition::Left,
 6361                                                        &self.left_dock,
 6362                                                        window,
 6363                                                        cx,
 6364                                                    ))
 6365                                                    .child(
 6366                                                        div()
 6367                                                            .flex()
 6368                                                            .flex_col()
 6369                                                            .flex_1()
 6370                                                            .overflow_hidden()
 6371                                                            .child(
 6372                                                                h_flex()
 6373                                                                    .flex_1()
 6374                                                                    .when_some(
 6375                                                                        paddings.0,
 6376                                                                        |this, p| {
 6377                                                                            this.child(
 6378                                                                                p.border_r_1(),
 6379                                                                            )
 6380                                                                        },
 6381                                                                    )
 6382                                                                    .child(self.center.render(
 6383                                                                        self.zoomed.as_ref(),
 6384                                                                        &PaneRenderContext {
 6385                                                                            follower_states:
 6386                                                                                &self.follower_states,
 6387                                                                            active_call: self.active_call(),
 6388                                                                            active_pane: &self.active_pane,
 6389                                                                            app_state: &self.app_state,
 6390                                                                            project: &self.project,
 6391                                                                            workspace: &self.weak_self,
 6392                                                                        },
 6393                                                                        window,
 6394                                                                        cx,
 6395                                                                    ))
 6396                                                                    .when_some(
 6397                                                                        paddings.1,
 6398                                                                        |this, p| {
 6399                                                                            this.child(
 6400                                                                                p.border_l_1(),
 6401                                                                            )
 6402                                                                        },
 6403                                                                    ),
 6404                                                            ),
 6405                                                    )
 6406                                                    .children(self.render_dock(
 6407                                                        DockPosition::Right,
 6408                                                        &self.right_dock,
 6409                                                        window,
 6410                                                        cx,
 6411                                                    )),
 6412                                            )
 6413                                            .child(div().w_full().children(self.render_dock(
 6414                                                DockPosition::Bottom,
 6415                                                &self.bottom_dock,
 6416                                                window,
 6417                                                cx
 6418                                            ))),
 6419
 6420                                        BottomDockLayout::LeftAligned => div()
 6421                                            .flex()
 6422                                            .flex_row()
 6423                                            .h_full()
 6424                                            .child(
 6425                                                div()
 6426                                                    .flex()
 6427                                                    .flex_col()
 6428                                                    .flex_1()
 6429                                                    .h_full()
 6430                                                    .child(
 6431                                                        div()
 6432                                                            .flex()
 6433                                                            .flex_row()
 6434                                                            .flex_1()
 6435                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 6436                                                            .child(
 6437                                                                div()
 6438                                                                    .flex()
 6439                                                                    .flex_col()
 6440                                                                    .flex_1()
 6441                                                                    .overflow_hidden()
 6442                                                                    .child(
 6443                                                                        h_flex()
 6444                                                                            .flex_1()
 6445                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6446                                                                            .child(self.center.render(
 6447                                                                                self.zoomed.as_ref(),
 6448                                                                                &PaneRenderContext {
 6449                                                                                    follower_states:
 6450                                                                                        &self.follower_states,
 6451                                                                                    active_call: self.active_call(),
 6452                                                                                    active_pane: &self.active_pane,
 6453                                                                                    app_state: &self.app_state,
 6454                                                                                    project: &self.project,
 6455                                                                                    workspace: &self.weak_self,
 6456                                                                                },
 6457                                                                                window,
 6458                                                                                cx,
 6459                                                                            ))
 6460                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6461                                                                    )
 6462                                                            )
 6463                                                    )
 6464                                                    .child(
 6465                                                        div()
 6466                                                            .w_full()
 6467                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6468                                                    ),
 6469                                            )
 6470                                            .children(self.render_dock(
 6471                                                DockPosition::Right,
 6472                                                &self.right_dock,
 6473                                                window,
 6474                                                cx,
 6475                                            )),
 6476
 6477                                        BottomDockLayout::RightAligned => div()
 6478                                            .flex()
 6479                                            .flex_row()
 6480                                            .h_full()
 6481                                            .children(self.render_dock(
 6482                                                DockPosition::Left,
 6483                                                &self.left_dock,
 6484                                                window,
 6485                                                cx,
 6486                                            ))
 6487                                            .child(
 6488                                                div()
 6489                                                    .flex()
 6490                                                    .flex_col()
 6491                                                    .flex_1()
 6492                                                    .h_full()
 6493                                                    .child(
 6494                                                        div()
 6495                                                            .flex()
 6496                                                            .flex_row()
 6497                                                            .flex_1()
 6498                                                            .child(
 6499                                                                div()
 6500                                                                    .flex()
 6501                                                                    .flex_col()
 6502                                                                    .flex_1()
 6503                                                                    .overflow_hidden()
 6504                                                                    .child(
 6505                                                                        h_flex()
 6506                                                                            .flex_1()
 6507                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6508                                                                            .child(self.center.render(
 6509                                                                                self.zoomed.as_ref(),
 6510                                                                                &PaneRenderContext {
 6511                                                                                    follower_states:
 6512                                                                                        &self.follower_states,
 6513                                                                                    active_call: self.active_call(),
 6514                                                                                    active_pane: &self.active_pane,
 6515                                                                                    app_state: &self.app_state,
 6516                                                                                    project: &self.project,
 6517                                                                                    workspace: &self.weak_self,
 6518                                                                                },
 6519                                                                                window,
 6520                                                                                cx,
 6521                                                                            ))
 6522                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6523                                                                    )
 6524                                                            )
 6525                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 6526                                                    )
 6527                                                    .child(
 6528                                                        div()
 6529                                                            .w_full()
 6530                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6531                                                    ),
 6532                                            ),
 6533
 6534                                        BottomDockLayout::Contained => div()
 6535                                            .flex()
 6536                                            .flex_row()
 6537                                            .h_full()
 6538                                            .children(self.render_dock(
 6539                                                DockPosition::Left,
 6540                                                &self.left_dock,
 6541                                                window,
 6542                                                cx,
 6543                                            ))
 6544                                            .child(
 6545                                                div()
 6546                                                    .flex()
 6547                                                    .flex_col()
 6548                                                    .flex_1()
 6549                                                    .overflow_hidden()
 6550                                                    .child(
 6551                                                        h_flex()
 6552                                                            .flex_1()
 6553                                                            .when_some(paddings.0, |this, p| {
 6554                                                                this.child(p.border_r_1())
 6555                                                            })
 6556                                                            .child(self.center.render(
 6557                                                                self.zoomed.as_ref(),
 6558                                                                &PaneRenderContext {
 6559                                                                    follower_states:
 6560                                                                        &self.follower_states,
 6561                                                                    active_call: self.active_call(),
 6562                                                                    active_pane: &self.active_pane,
 6563                                                                    app_state: &self.app_state,
 6564                                                                    project: &self.project,
 6565                                                                    workspace: &self.weak_self,
 6566                                                                },
 6567                                                                window,
 6568                                                                cx,
 6569                                                            ))
 6570                                                            .when_some(paddings.1, |this, p| {
 6571                                                                this.child(p.border_l_1())
 6572                                                            }),
 6573                                                    )
 6574                                                    .children(self.render_dock(
 6575                                                        DockPosition::Bottom,
 6576                                                        &self.bottom_dock,
 6577                                                        window,
 6578                                                        cx,
 6579                                                    )),
 6580                                            )
 6581                                            .children(self.render_dock(
 6582                                                DockPosition::Right,
 6583                                                &self.right_dock,
 6584                                                window,
 6585                                                cx,
 6586                                            )),
 6587                                    }
 6588                                })
 6589                                .children(self.zoomed.as_ref().and_then(|view| {
 6590                                    let zoomed_view = view.upgrade()?;
 6591                                    let div = div()
 6592                                        .occlude()
 6593                                        .absolute()
 6594                                        .overflow_hidden()
 6595                                        .border_color(colors.border)
 6596                                        .bg(colors.background)
 6597                                        .child(zoomed_view)
 6598                                        .inset_0()
 6599                                        .shadow_lg();
 6600
 6601                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 6602                                       return Some(div);
 6603                                    }
 6604
 6605                                    Some(match self.zoomed_position {
 6606                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 6607                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 6608                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 6609                                        None => {
 6610                                            div.top_2().bottom_2().left_2().right_2().border_1()
 6611                                        }
 6612                                    })
 6613                                }))
 6614                                .children(self.render_notifications(window, cx)),
 6615                        )
 6616                        .child(self.status_bar.clone())
 6617                        .child(self.modal_layer.clone())
 6618                        .child(self.toast_layer.clone()),
 6619                ),
 6620            window,
 6621            cx,
 6622        )
 6623    }
 6624}
 6625
 6626impl WorkspaceStore {
 6627    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 6628        Self {
 6629            workspaces: Default::default(),
 6630            _subscriptions: vec![
 6631                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 6632                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 6633            ],
 6634            client,
 6635        }
 6636    }
 6637
 6638    pub fn update_followers(
 6639        &self,
 6640        project_id: Option<u64>,
 6641        update: proto::update_followers::Variant,
 6642        cx: &App,
 6643    ) -> Option<()> {
 6644        let active_call = ActiveCall::try_global(cx)?;
 6645        let room_id = active_call.read(cx).room()?.read(cx).id();
 6646        self.client
 6647            .send(proto::UpdateFollowers {
 6648                room_id,
 6649                project_id,
 6650                variant: Some(update),
 6651            })
 6652            .log_err()
 6653    }
 6654
 6655    pub async fn handle_follow(
 6656        this: Entity<Self>,
 6657        envelope: TypedEnvelope<proto::Follow>,
 6658        mut cx: AsyncApp,
 6659    ) -> Result<proto::FollowResponse> {
 6660        this.update(&mut cx, |this, cx| {
 6661            let follower = Follower {
 6662                project_id: envelope.payload.project_id,
 6663                peer_id: envelope.original_sender_id()?,
 6664            };
 6665
 6666            let mut response = proto::FollowResponse::default();
 6667            this.workspaces.retain(|workspace| {
 6668                workspace
 6669                    .update(cx, |workspace, window, cx| {
 6670                        let handler_response =
 6671                            workspace.handle_follow(follower.project_id, window, cx);
 6672                        if let Some(active_view) = handler_response.active_view
 6673                            && workspace.project.read(cx).remote_id() == follower.project_id
 6674                        {
 6675                            response.active_view = Some(active_view)
 6676                        }
 6677                    })
 6678                    .is_ok()
 6679            });
 6680
 6681            Ok(response)
 6682        })?
 6683    }
 6684
 6685    async fn handle_update_followers(
 6686        this: Entity<Self>,
 6687        envelope: TypedEnvelope<proto::UpdateFollowers>,
 6688        mut cx: AsyncApp,
 6689    ) -> Result<()> {
 6690        let leader_id = envelope.original_sender_id()?;
 6691        let update = envelope.payload;
 6692
 6693        this.update(&mut cx, |this, cx| {
 6694            this.workspaces.retain(|workspace| {
 6695                workspace
 6696                    .update(cx, |workspace, window, cx| {
 6697                        let project_id = workspace.project.read(cx).remote_id();
 6698                        if update.project_id != project_id && update.project_id.is_some() {
 6699                            return;
 6700                        }
 6701                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 6702                    })
 6703                    .is_ok()
 6704            });
 6705            Ok(())
 6706        })?
 6707    }
 6708
 6709    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 6710        &self.workspaces
 6711    }
 6712}
 6713
 6714impl ViewId {
 6715    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 6716        Ok(Self {
 6717            creator: message
 6718                .creator
 6719                .map(CollaboratorId::PeerId)
 6720                .context("creator is missing")?,
 6721            id: message.id,
 6722        })
 6723    }
 6724
 6725    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 6726        if let CollaboratorId::PeerId(peer_id) = self.creator {
 6727            Some(proto::ViewId {
 6728                creator: Some(peer_id),
 6729                id: self.id,
 6730            })
 6731        } else {
 6732            None
 6733        }
 6734    }
 6735}
 6736
 6737impl FollowerState {
 6738    fn pane(&self) -> &Entity<Pane> {
 6739        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 6740    }
 6741}
 6742
 6743pub trait WorkspaceHandle {
 6744    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 6745}
 6746
 6747impl WorkspaceHandle for Entity<Workspace> {
 6748    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 6749        self.read(cx)
 6750            .worktrees(cx)
 6751            .flat_map(|worktree| {
 6752                let worktree_id = worktree.read(cx).id();
 6753                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 6754                    worktree_id,
 6755                    path: f.path.clone(),
 6756                })
 6757            })
 6758            .collect::<Vec<_>>()
 6759    }
 6760}
 6761
 6762pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 6763    DB.last_workspace().await.log_err().flatten()
 6764}
 6765
 6766pub fn last_session_workspace_locations(
 6767    last_session_id: &str,
 6768    last_session_window_stack: Option<Vec<WindowId>>,
 6769) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 6770    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 6771        .log_err()
 6772}
 6773
 6774actions!(
 6775    collab,
 6776    [
 6777        /// Opens the channel notes for the current call.
 6778        ///
 6779        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 6780        /// can be copied via "Copy link to section" in the context menu of the channel notes
 6781        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 6782        OpenChannelNotes,
 6783        /// Mutes your microphone.
 6784        Mute,
 6785        /// Deafens yourself (mute both microphone and speakers).
 6786        Deafen,
 6787        /// Leaves the current call.
 6788        LeaveCall,
 6789        /// Shares the current project with collaborators.
 6790        ShareProject,
 6791        /// Shares your screen with collaborators.
 6792        ScreenShare
 6793    ]
 6794);
 6795actions!(
 6796    zed,
 6797    [
 6798        /// Opens the Zed log file.
 6799        OpenLog
 6800    ]
 6801);
 6802
 6803async fn join_channel_internal(
 6804    channel_id: ChannelId,
 6805    app_state: &Arc<AppState>,
 6806    requesting_window: Option<WindowHandle<Workspace>>,
 6807    active_call: &Entity<ActiveCall>,
 6808    cx: &mut AsyncApp,
 6809) -> Result<bool> {
 6810    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 6811        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 6812            return (false, None);
 6813        };
 6814
 6815        let already_in_channel = room.channel_id() == Some(channel_id);
 6816        let should_prompt = room.is_sharing_project()
 6817            && !room.remote_participants().is_empty()
 6818            && !already_in_channel;
 6819        let open_room = if already_in_channel {
 6820            active_call.room().cloned()
 6821        } else {
 6822            None
 6823        };
 6824        (should_prompt, open_room)
 6825    })?;
 6826
 6827    if let Some(room) = open_room {
 6828        let task = room.update(cx, |room, cx| {
 6829            if let Some((project, host)) = room.most_active_project(cx) {
 6830                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 6831            }
 6832
 6833            None
 6834        })?;
 6835        if let Some(task) = task {
 6836            task.await?;
 6837        }
 6838        return anyhow::Ok(true);
 6839    }
 6840
 6841    if should_prompt {
 6842        if let Some(workspace) = requesting_window {
 6843            let answer = workspace
 6844                .update(cx, |_, window, cx| {
 6845                    window.prompt(
 6846                        PromptLevel::Warning,
 6847                        "Do you want to switch channels?",
 6848                        Some("Leaving this call will unshare your current project."),
 6849                        &["Yes, Join Channel", "Cancel"],
 6850                        cx,
 6851                    )
 6852                })?
 6853                .await;
 6854
 6855            if answer == Ok(1) {
 6856                return Ok(false);
 6857            }
 6858        } else {
 6859            return Ok(false); // unreachable!() hopefully
 6860        }
 6861    }
 6862
 6863    let client = cx.update(|cx| active_call.read(cx).client())?;
 6864
 6865    let mut client_status = client.status();
 6866
 6867    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 6868    'outer: loop {
 6869        let Some(status) = client_status.recv().await else {
 6870            anyhow::bail!("error connecting");
 6871        };
 6872
 6873        match status {
 6874            Status::Connecting
 6875            | Status::Authenticating
 6876            | Status::Authenticated
 6877            | Status::Reconnecting
 6878            | Status::Reauthenticating => continue,
 6879            Status::Connected { .. } => break 'outer,
 6880            Status::SignedOut | Status::AuthenticationError => {
 6881                return Err(ErrorCode::SignedOut.into());
 6882            }
 6883            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 6884            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 6885                return Err(ErrorCode::Disconnected.into());
 6886            }
 6887        }
 6888    }
 6889
 6890    let room = active_call
 6891        .update(cx, |active_call, cx| {
 6892            active_call.join_channel(channel_id, cx)
 6893        })?
 6894        .await?;
 6895
 6896    let Some(room) = room else {
 6897        return anyhow::Ok(true);
 6898    };
 6899
 6900    room.update(cx, |room, _| room.room_update_completed())?
 6901        .await;
 6902
 6903    let task = room.update(cx, |room, cx| {
 6904        if let Some((project, host)) = room.most_active_project(cx) {
 6905            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 6906        }
 6907
 6908        // If you are the first to join a channel, see if you should share your project.
 6909        if room.remote_participants().is_empty()
 6910            && !room.local_participant_is_guest()
 6911            && let Some(workspace) = requesting_window
 6912        {
 6913            let project = workspace.update(cx, |workspace, _, cx| {
 6914                let project = workspace.project.read(cx);
 6915
 6916                if !CallSettings::get_global(cx).share_on_join {
 6917                    return None;
 6918                }
 6919
 6920                if (project.is_local() || project.is_via_remote_server())
 6921                    && project.visible_worktrees(cx).any(|tree| {
 6922                        tree.read(cx)
 6923                            .root_entry()
 6924                            .is_some_and(|entry| entry.is_dir())
 6925                    })
 6926                {
 6927                    Some(workspace.project.clone())
 6928                } else {
 6929                    None
 6930                }
 6931            });
 6932            if let Ok(Some(project)) = project {
 6933                return Some(cx.spawn(async move |room, cx| {
 6934                    room.update(cx, |room, cx| room.share_project(project, cx))?
 6935                        .await?;
 6936                    Ok(())
 6937                }));
 6938            }
 6939        }
 6940
 6941        None
 6942    })?;
 6943    if let Some(task) = task {
 6944        task.await?;
 6945        return anyhow::Ok(true);
 6946    }
 6947    anyhow::Ok(false)
 6948}
 6949
 6950pub fn join_channel(
 6951    channel_id: ChannelId,
 6952    app_state: Arc<AppState>,
 6953    requesting_window: Option<WindowHandle<Workspace>>,
 6954    cx: &mut App,
 6955) -> Task<Result<()>> {
 6956    let active_call = ActiveCall::global(cx);
 6957    cx.spawn(async move |cx| {
 6958        let result = join_channel_internal(
 6959            channel_id,
 6960            &app_state,
 6961            requesting_window,
 6962            &active_call,
 6963             cx,
 6964        )
 6965            .await;
 6966
 6967        // join channel succeeded, and opened a window
 6968        if matches!(result, Ok(true)) {
 6969            return anyhow::Ok(());
 6970        }
 6971
 6972        // find an existing workspace to focus and show call controls
 6973        let mut active_window =
 6974            requesting_window.or_else(|| activate_any_workspace_window( cx));
 6975        if active_window.is_none() {
 6976            // no open workspaces, make one to show the error in (blergh)
 6977            let (window_handle, _) = cx
 6978                .update(|cx| {
 6979                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 6980                })?
 6981                .await?;
 6982
 6983            if result.is_ok() {
 6984                cx.update(|cx| {
 6985                    cx.dispatch_action(&OpenChannelNotes);
 6986                }).log_err();
 6987            }
 6988
 6989            active_window = Some(window_handle);
 6990        }
 6991
 6992        if let Err(err) = result {
 6993            log::error!("failed to join channel: {}", err);
 6994            if let Some(active_window) = active_window {
 6995                active_window
 6996                    .update(cx, |_, window, cx| {
 6997                        let detail: SharedString = match err.error_code() {
 6998                            ErrorCode::SignedOut => {
 6999                                "Please sign in to continue.".into()
 7000                            }
 7001                            ErrorCode::UpgradeRequired => {
 7002                                "Your are running an unsupported version of Zed. Please update to continue.".into()
 7003                            }
 7004                            ErrorCode::NoSuchChannel => {
 7005                                "No matching channel was found. Please check the link and try again.".into()
 7006                            }
 7007                            ErrorCode::Forbidden => {
 7008                                "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
 7009                            }
 7010                            ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
 7011                            _ => format!("{}\n\nPlease try again.", err).into(),
 7012                        };
 7013                        window.prompt(
 7014                            PromptLevel::Critical,
 7015                            "Failed to join channel",
 7016                            Some(&detail),
 7017                            &["Ok"],
 7018                        cx)
 7019                    })?
 7020                    .await
 7021                    .ok();
 7022            }
 7023        }
 7024
 7025        // return ok, we showed the error to the user.
 7026        anyhow::Ok(())
 7027    })
 7028}
 7029
 7030pub async fn get_any_active_workspace(
 7031    app_state: Arc<AppState>,
 7032    mut cx: AsyncApp,
 7033) -> anyhow::Result<WindowHandle<Workspace>> {
 7034    // find an existing workspace to focus and show call controls
 7035    let active_window = activate_any_workspace_window(&mut cx);
 7036    if active_window.is_none() {
 7037        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 7038            .await?;
 7039    }
 7040    activate_any_workspace_window(&mut cx).context("could not open zed")
 7041}
 7042
 7043fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7044    cx.update(|cx| {
 7045        if let Some(workspace_window) = cx
 7046            .active_window()
 7047            .and_then(|window| window.downcast::<Workspace>())
 7048        {
 7049            return Some(workspace_window);
 7050        }
 7051
 7052        for window in cx.windows() {
 7053            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7054                workspace_window
 7055                    .update(cx, |_, window, _| window.activate_window())
 7056                    .ok();
 7057                return Some(workspace_window);
 7058            }
 7059        }
 7060        None
 7061    })
 7062    .ok()
 7063    .flatten()
 7064}
 7065
 7066pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7067    cx.windows()
 7068        .into_iter()
 7069        .filter_map(|window| window.downcast::<Workspace>())
 7070        .filter(|workspace| {
 7071            workspace
 7072                .read(cx)
 7073                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7074        })
 7075        .collect()
 7076}
 7077
 7078#[derive(Default)]
 7079pub struct OpenOptions {
 7080    pub visible: Option<OpenVisible>,
 7081    pub focus: Option<bool>,
 7082    pub open_new_workspace: Option<bool>,
 7083    pub replace_window: Option<WindowHandle<Workspace>>,
 7084    pub env: Option<HashMap<String, String>>,
 7085}
 7086
 7087#[allow(clippy::type_complexity)]
 7088pub fn open_paths(
 7089    abs_paths: &[PathBuf],
 7090    app_state: Arc<AppState>,
 7091    open_options: OpenOptions,
 7092    cx: &mut App,
 7093) -> Task<
 7094    anyhow::Result<(
 7095        WindowHandle<Workspace>,
 7096        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7097    )>,
 7098> {
 7099    let abs_paths = abs_paths.to_vec();
 7100    let mut existing = None;
 7101    let mut best_match = None;
 7102    let mut open_visible = OpenVisible::All;
 7103
 7104    cx.spawn(async move |cx| {
 7105        if open_options.open_new_workspace != Some(true) {
 7106            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7107            let all_metadatas = futures::future::join_all(all_paths)
 7108                .await
 7109                .into_iter()
 7110                .filter_map(|result| result.ok().flatten())
 7111                .collect::<Vec<_>>();
 7112
 7113            cx.update(|cx| {
 7114                for window in local_workspace_windows(cx) {
 7115                    if let Ok(workspace) = window.read(cx) {
 7116                        let m = workspace.project.read(cx).visibility_for_paths(
 7117                            &abs_paths,
 7118                            &all_metadatas,
 7119                            open_options.open_new_workspace == None,
 7120                            cx,
 7121                        );
 7122                        if m > best_match {
 7123                            existing = Some(window);
 7124                            best_match = m;
 7125                        } else if best_match.is_none()
 7126                            && open_options.open_new_workspace == Some(false)
 7127                        {
 7128                            existing = Some(window)
 7129                        }
 7130                    }
 7131                }
 7132            })?;
 7133
 7134            if open_options.open_new_workspace.is_none()
 7135                && existing.is_none()
 7136                && all_metadatas.iter().all(|file| !file.is_dir)
 7137            {
 7138                cx.update(|cx| {
 7139                    if let Some(window) = cx
 7140                        .active_window()
 7141                        .and_then(|window| window.downcast::<Workspace>())
 7142                        && let Ok(workspace) = window.read(cx)
 7143                    {
 7144                        let project = workspace.project().read(cx);
 7145                        if project.is_local() && !project.is_via_collab() {
 7146                            existing = Some(window);
 7147                            open_visible = OpenVisible::None;
 7148                            return;
 7149                        }
 7150                    }
 7151                    for window in local_workspace_windows(cx) {
 7152                        if let Ok(workspace) = window.read(cx) {
 7153                            let project = workspace.project().read(cx);
 7154                            if project.is_via_collab() {
 7155                                continue;
 7156                            }
 7157                            existing = Some(window);
 7158                            open_visible = OpenVisible::None;
 7159                            break;
 7160                        }
 7161                    }
 7162                })?;
 7163            }
 7164        }
 7165
 7166        if let Some(existing) = existing {
 7167            let open_task = existing
 7168                .update(cx, |workspace, window, cx| {
 7169                    window.activate_window();
 7170                    workspace.open_paths(
 7171                        abs_paths,
 7172                        OpenOptions {
 7173                            visible: Some(open_visible),
 7174                            ..Default::default()
 7175                        },
 7176                        None,
 7177                        window,
 7178                        cx,
 7179                    )
 7180                })?
 7181                .await;
 7182
 7183            _ = existing.update(cx, |workspace, _, cx| {
 7184                for item in open_task.iter().flatten() {
 7185                    if let Err(e) = item {
 7186                        workspace.show_error(&e, cx);
 7187                    }
 7188                }
 7189            });
 7190
 7191            Ok((existing, open_task))
 7192        } else {
 7193            cx.update(move |cx| {
 7194                Workspace::new_local(
 7195                    abs_paths,
 7196                    app_state.clone(),
 7197                    open_options.replace_window,
 7198                    open_options.env,
 7199                    cx,
 7200                )
 7201            })?
 7202            .await
 7203        }
 7204    })
 7205}
 7206
 7207pub fn open_new(
 7208    open_options: OpenOptions,
 7209    app_state: Arc<AppState>,
 7210    cx: &mut App,
 7211    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7212) -> Task<anyhow::Result<()>> {
 7213    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7214    cx.spawn(async move |cx| {
 7215        let (workspace, opened_paths) = task.await?;
 7216        workspace.update(cx, |workspace, window, cx| {
 7217            if opened_paths.is_empty() {
 7218                init(workspace, window, cx)
 7219            }
 7220        })?;
 7221        Ok(())
 7222    })
 7223}
 7224
 7225pub fn create_and_open_local_file(
 7226    path: &'static Path,
 7227    window: &mut Window,
 7228    cx: &mut Context<Workspace>,
 7229    default_content: impl 'static + Send + FnOnce() -> Rope,
 7230) -> Task<Result<Box<dyn ItemHandle>>> {
 7231    cx.spawn_in(window, async move |workspace, cx| {
 7232        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7233        if !fs.is_file(path).await {
 7234            fs.create_file(path, Default::default()).await?;
 7235            fs.save(path, &default_content(), Default::default())
 7236                .await?;
 7237        }
 7238
 7239        let mut items = workspace
 7240            .update_in(cx, |workspace, window, cx| {
 7241                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7242                    workspace.open_paths(
 7243                        vec![path.to_path_buf()],
 7244                        OpenOptions {
 7245                            visible: Some(OpenVisible::None),
 7246                            ..Default::default()
 7247                        },
 7248                        None,
 7249                        window,
 7250                        cx,
 7251                    )
 7252                })
 7253            })?
 7254            .await?
 7255            .await;
 7256
 7257        let item = items.pop().flatten();
 7258        item.with_context(|| format!("path {path:?} is not a file"))?
 7259    })
 7260}
 7261
 7262pub fn open_ssh_project_with_new_connection(
 7263    window: WindowHandle<Workspace>,
 7264    connection_options: SshConnectionOptions,
 7265    cancel_rx: oneshot::Receiver<()>,
 7266    delegate: Arc<dyn RemoteClientDelegate>,
 7267    app_state: Arc<AppState>,
 7268    paths: Vec<PathBuf>,
 7269    cx: &mut App,
 7270) -> Task<Result<()>> {
 7271    cx.spawn(async move |cx| {
 7272        let (workspace_id, serialized_workspace) =
 7273            serialize_ssh_project(connection_options.clone(), paths.clone(), cx).await?;
 7274
 7275        let session = match cx
 7276            .update(|cx| {
 7277                remote::RemoteClient::ssh(
 7278                    ConnectionIdentifier::Workspace(workspace_id.0),
 7279                    connection_options,
 7280                    cancel_rx,
 7281                    delegate,
 7282                    cx,
 7283                )
 7284            })?
 7285            .await?
 7286        {
 7287            Some(result) => result,
 7288            None => return Ok(()),
 7289        };
 7290
 7291        let project = cx.update(|cx| {
 7292            project::Project::remote(
 7293                session,
 7294                app_state.client.clone(),
 7295                app_state.node_runtime.clone(),
 7296                app_state.user_store.clone(),
 7297                app_state.languages.clone(),
 7298                app_state.fs.clone(),
 7299                cx,
 7300            )
 7301        })?;
 7302
 7303        open_ssh_project_inner(
 7304            project,
 7305            paths,
 7306            workspace_id,
 7307            serialized_workspace,
 7308            app_state,
 7309            window,
 7310            cx,
 7311        )
 7312        .await
 7313    })
 7314}
 7315
 7316pub fn open_ssh_project_with_existing_connection(
 7317    connection_options: SshConnectionOptions,
 7318    project: Entity<Project>,
 7319    paths: Vec<PathBuf>,
 7320    app_state: Arc<AppState>,
 7321    window: WindowHandle<Workspace>,
 7322    cx: &mut AsyncApp,
 7323) -> Task<Result<()>> {
 7324    cx.spawn(async move |cx| {
 7325        let (workspace_id, serialized_workspace) =
 7326            serialize_ssh_project(connection_options.clone(), paths.clone(), cx).await?;
 7327
 7328        open_ssh_project_inner(
 7329            project,
 7330            paths,
 7331            workspace_id,
 7332            serialized_workspace,
 7333            app_state,
 7334            window,
 7335            cx,
 7336        )
 7337        .await
 7338    })
 7339}
 7340
 7341async fn open_ssh_project_inner(
 7342    project: Entity<Project>,
 7343    paths: Vec<PathBuf>,
 7344    workspace_id: WorkspaceId,
 7345    serialized_workspace: Option<SerializedWorkspace>,
 7346    app_state: Arc<AppState>,
 7347    window: WindowHandle<Workspace>,
 7348    cx: &mut AsyncApp,
 7349) -> Result<()> {
 7350    let toolchains = DB.toolchains(workspace_id).await?;
 7351    for (toolchain, worktree_id, path) in toolchains {
 7352        project
 7353            .update(cx, |this, cx| {
 7354                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7355            })?
 7356            .await;
 7357    }
 7358    let mut project_paths_to_open = vec![];
 7359    let mut project_path_errors = vec![];
 7360
 7361    for path in paths {
 7362        let result = cx
 7363            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7364            .await;
 7365        match result {
 7366            Ok((_, project_path)) => {
 7367                project_paths_to_open.push((path.clone(), Some(project_path)));
 7368            }
 7369            Err(error) => {
 7370                project_path_errors.push(error);
 7371            }
 7372        };
 7373    }
 7374
 7375    if project_paths_to_open.is_empty() {
 7376        return Err(project_path_errors.pop().context("no paths given")?);
 7377    }
 7378
 7379    if let Some(detach_session_task) = window
 7380        .update(cx, |_workspace, window, cx| {
 7381            cx.spawn_in(window, async move |this, cx| {
 7382                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 7383            })
 7384        })
 7385        .ok()
 7386    {
 7387        detach_session_task.await.ok();
 7388    }
 7389
 7390    cx.update_window(window.into(), |_, window, cx| {
 7391        window.replace_root(cx, |window, cx| {
 7392            telemetry::event!("SSH Project Opened");
 7393
 7394            let mut workspace =
 7395                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7396            workspace.update_history(cx);
 7397
 7398            if let Some(ref serialized) = serialized_workspace {
 7399                workspace.centered_layout = serialized.centered_layout;
 7400            }
 7401
 7402            workspace
 7403        });
 7404    })?;
 7405
 7406    window
 7407        .update(cx, |_, window, cx| {
 7408            window.activate_window();
 7409            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7410        })?
 7411        .await?;
 7412
 7413    window.update(cx, |workspace, _, cx| {
 7414        for error in project_path_errors {
 7415            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7416                if let Some(path) = error.error_tag("path") {
 7417                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7418                }
 7419            } else {
 7420                workspace.show_error(&error, cx)
 7421            }
 7422        }
 7423    })?;
 7424
 7425    Ok(())
 7426}
 7427
 7428fn serialize_ssh_project(
 7429    connection_options: SshConnectionOptions,
 7430    paths: Vec<PathBuf>,
 7431    cx: &AsyncApp,
 7432) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7433    cx.background_spawn(async move {
 7434        let ssh_connection_id = persistence::DB
 7435            .get_or_create_ssh_connection(
 7436                connection_options.host.clone(),
 7437                connection_options.port,
 7438                connection_options.username.clone(),
 7439            )
 7440            .await?;
 7441
 7442        let serialized_workspace =
 7443            persistence::DB.ssh_workspace_for_roots(&paths, ssh_connection_id);
 7444
 7445        let workspace_id = if let Some(workspace_id) =
 7446            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7447        {
 7448            workspace_id
 7449        } else {
 7450            persistence::DB.next_id().await?
 7451        };
 7452
 7453        Ok((workspace_id, serialized_workspace))
 7454    })
 7455}
 7456
 7457pub fn join_in_room_project(
 7458    project_id: u64,
 7459    follow_user_id: u64,
 7460    app_state: Arc<AppState>,
 7461    cx: &mut App,
 7462) -> Task<Result<()>> {
 7463    let windows = cx.windows();
 7464    cx.spawn(async move |cx| {
 7465        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7466            window_handle
 7467                .downcast::<Workspace>()
 7468                .and_then(|window_handle| {
 7469                    window_handle
 7470                        .update(cx, |workspace, _window, cx| {
 7471                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7472                                Some(window_handle)
 7473                            } else {
 7474                                None
 7475                            }
 7476                        })
 7477                        .unwrap_or(None)
 7478                })
 7479        });
 7480
 7481        let workspace = if let Some(existing_workspace) = existing_workspace {
 7482            existing_workspace
 7483        } else {
 7484            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7485            let room = active_call
 7486                .read_with(cx, |call, _| call.room().cloned())?
 7487                .context("not in a call")?;
 7488            let project = room
 7489                .update(cx, |room, cx| {
 7490                    room.join_project(
 7491                        project_id,
 7492                        app_state.languages.clone(),
 7493                        app_state.fs.clone(),
 7494                        cx,
 7495                    )
 7496                })?
 7497                .await?;
 7498
 7499            let window_bounds_override = window_bounds_env_override();
 7500            cx.update(|cx| {
 7501                let mut options = (app_state.build_window_options)(None, cx);
 7502                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7503                cx.open_window(options, |window, cx| {
 7504                    cx.new(|cx| {
 7505                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7506                    })
 7507                })
 7508            })??
 7509        };
 7510
 7511        workspace.update(cx, |workspace, window, cx| {
 7512            cx.activate(true);
 7513            window.activate_window();
 7514
 7515            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7516                let follow_peer_id = room
 7517                    .read(cx)
 7518                    .remote_participants()
 7519                    .iter()
 7520                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7521                    .map(|(_, p)| p.peer_id)
 7522                    .or_else(|| {
 7523                        // If we couldn't follow the given user, follow the host instead.
 7524                        let collaborator = workspace
 7525                            .project()
 7526                            .read(cx)
 7527                            .collaborators()
 7528                            .values()
 7529                            .find(|collaborator| collaborator.is_host)?;
 7530                        Some(collaborator.peer_id)
 7531                    });
 7532
 7533                if let Some(follow_peer_id) = follow_peer_id {
 7534                    workspace.follow(follow_peer_id, window, cx);
 7535                }
 7536            }
 7537        })?;
 7538
 7539        anyhow::Ok(())
 7540    })
 7541}
 7542
 7543pub fn reload(cx: &mut App) {
 7544    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7545    let mut workspace_windows = cx
 7546        .windows()
 7547        .into_iter()
 7548        .filter_map(|window| window.downcast::<Workspace>())
 7549        .collect::<Vec<_>>();
 7550
 7551    // If multiple windows have unsaved changes, and need a save prompt,
 7552    // prompt in the active window before switching to a different window.
 7553    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7554
 7555    let mut prompt = None;
 7556    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7557        prompt = window
 7558            .update(cx, |_, window, cx| {
 7559                window.prompt(
 7560                    PromptLevel::Info,
 7561                    "Are you sure you want to restart?",
 7562                    None,
 7563                    &["Restart", "Cancel"],
 7564                    cx,
 7565                )
 7566            })
 7567            .ok();
 7568    }
 7569
 7570    cx.spawn(async move |cx| {
 7571        if let Some(prompt) = prompt {
 7572            let answer = prompt.await?;
 7573            if answer != 0 {
 7574                return Ok(());
 7575            }
 7576        }
 7577
 7578        // If the user cancels any save prompt, then keep the app open.
 7579        for window in workspace_windows {
 7580            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7581                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7582            }) && !should_close.await?
 7583            {
 7584                return Ok(());
 7585            }
 7586        }
 7587        cx.update(|cx| cx.restart())
 7588    })
 7589    .detach_and_log_err(cx);
 7590}
 7591
 7592fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7593    let mut parts = value.split(',');
 7594    let x: usize = parts.next()?.parse().ok()?;
 7595    let y: usize = parts.next()?.parse().ok()?;
 7596    Some(point(px(x as f32), px(y as f32)))
 7597}
 7598
 7599fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7600    let mut parts = value.split(',');
 7601    let width: usize = parts.next()?.parse().ok()?;
 7602    let height: usize = parts.next()?.parse().ok()?;
 7603    Some(size(px(width as f32), px(height as f32)))
 7604}
 7605
 7606/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7607pub fn client_side_decorations(
 7608    element: impl IntoElement,
 7609    window: &mut Window,
 7610    cx: &mut App,
 7611) -> Stateful<Div> {
 7612    const BORDER_SIZE: Pixels = px(1.0);
 7613    let decorations = window.window_decorations();
 7614
 7615    match decorations {
 7616        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7617        Decorations::Server => window.set_client_inset(px(0.0)),
 7618    }
 7619
 7620    struct GlobalResizeEdge(ResizeEdge);
 7621    impl Global for GlobalResizeEdge {}
 7622
 7623    div()
 7624        .id("window-backdrop")
 7625        .bg(transparent_black())
 7626        .map(|div| match decorations {
 7627            Decorations::Server => div,
 7628            Decorations::Client { tiling, .. } => div
 7629                .when(!(tiling.top || tiling.right), |div| {
 7630                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7631                })
 7632                .when(!(tiling.top || tiling.left), |div| {
 7633                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7634                })
 7635                .when(!(tiling.bottom || tiling.right), |div| {
 7636                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7637                })
 7638                .when(!(tiling.bottom || tiling.left), |div| {
 7639                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7640                })
 7641                .when(!tiling.top, |div| {
 7642                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7643                })
 7644                .when(!tiling.bottom, |div| {
 7645                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7646                })
 7647                .when(!tiling.left, |div| {
 7648                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7649                })
 7650                .when(!tiling.right, |div| {
 7651                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7652                })
 7653                .on_mouse_move(move |e, window, cx| {
 7654                    let size = window.window_bounds().get_bounds().size;
 7655                    let pos = e.position;
 7656
 7657                    let new_edge =
 7658                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 7659
 7660                    let edge = cx.try_global::<GlobalResizeEdge>();
 7661                    if new_edge != edge.map(|edge| edge.0) {
 7662                        window
 7663                            .window_handle()
 7664                            .update(cx, |workspace, _, cx| {
 7665                                cx.notify(workspace.entity_id());
 7666                            })
 7667                            .ok();
 7668                    }
 7669                })
 7670                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 7671                    let size = window.window_bounds().get_bounds().size;
 7672                    let pos = e.position;
 7673
 7674                    let edge = match resize_edge(
 7675                        pos,
 7676                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 7677                        size,
 7678                        tiling,
 7679                    ) {
 7680                        Some(value) => value,
 7681                        None => return,
 7682                    };
 7683
 7684                    window.start_window_resize(edge);
 7685                }),
 7686        })
 7687        .size_full()
 7688        .child(
 7689            div()
 7690                .cursor(CursorStyle::Arrow)
 7691                .map(|div| match decorations {
 7692                    Decorations::Server => div,
 7693                    Decorations::Client { tiling } => div
 7694                        .border_color(cx.theme().colors().border)
 7695                        .when(!(tiling.top || tiling.right), |div| {
 7696                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7697                        })
 7698                        .when(!(tiling.top || tiling.left), |div| {
 7699                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7700                        })
 7701                        .when(!(tiling.bottom || tiling.right), |div| {
 7702                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7703                        })
 7704                        .when(!(tiling.bottom || tiling.left), |div| {
 7705                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7706                        })
 7707                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 7708                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 7709                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 7710                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 7711                        .when(!tiling.is_tiled(), |div| {
 7712                            div.shadow(vec![gpui::BoxShadow {
 7713                                color: Hsla {
 7714                                    h: 0.,
 7715                                    s: 0.,
 7716                                    l: 0.,
 7717                                    a: 0.4,
 7718                                },
 7719                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 7720                                spread_radius: px(0.),
 7721                                offset: point(px(0.0), px(0.0)),
 7722                            }])
 7723                        }),
 7724                })
 7725                .on_mouse_move(|_e, _, cx| {
 7726                    cx.stop_propagation();
 7727                })
 7728                .size_full()
 7729                .child(element),
 7730        )
 7731        .map(|div| match decorations {
 7732            Decorations::Server => div,
 7733            Decorations::Client { tiling, .. } => div.child(
 7734                canvas(
 7735                    |_bounds, window, _| {
 7736                        window.insert_hitbox(
 7737                            Bounds::new(
 7738                                point(px(0.0), px(0.0)),
 7739                                window.window_bounds().get_bounds().size,
 7740                            ),
 7741                            HitboxBehavior::Normal,
 7742                        )
 7743                    },
 7744                    move |_bounds, hitbox, window, cx| {
 7745                        let mouse = window.mouse_position();
 7746                        let size = window.window_bounds().get_bounds().size;
 7747                        let Some(edge) =
 7748                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 7749                        else {
 7750                            return;
 7751                        };
 7752                        cx.set_global(GlobalResizeEdge(edge));
 7753                        window.set_cursor_style(
 7754                            match edge {
 7755                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 7756                                ResizeEdge::Left | ResizeEdge::Right => {
 7757                                    CursorStyle::ResizeLeftRight
 7758                                }
 7759                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 7760                                    CursorStyle::ResizeUpLeftDownRight
 7761                                }
 7762                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 7763                                    CursorStyle::ResizeUpRightDownLeft
 7764                                }
 7765                            },
 7766                            &hitbox,
 7767                        );
 7768                    },
 7769                )
 7770                .size_full()
 7771                .absolute(),
 7772            ),
 7773        })
 7774}
 7775
 7776fn resize_edge(
 7777    pos: Point<Pixels>,
 7778    shadow_size: Pixels,
 7779    window_size: Size<Pixels>,
 7780    tiling: Tiling,
 7781) -> Option<ResizeEdge> {
 7782    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 7783    if bounds.contains(&pos) {
 7784        return None;
 7785    }
 7786
 7787    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 7788    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 7789    if !tiling.top && top_left_bounds.contains(&pos) {
 7790        return Some(ResizeEdge::TopLeft);
 7791    }
 7792
 7793    let top_right_bounds = Bounds::new(
 7794        Point::new(window_size.width - corner_size.width, px(0.)),
 7795        corner_size,
 7796    );
 7797    if !tiling.top && top_right_bounds.contains(&pos) {
 7798        return Some(ResizeEdge::TopRight);
 7799    }
 7800
 7801    let bottom_left_bounds = Bounds::new(
 7802        Point::new(px(0.), window_size.height - corner_size.height),
 7803        corner_size,
 7804    );
 7805    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 7806        return Some(ResizeEdge::BottomLeft);
 7807    }
 7808
 7809    let bottom_right_bounds = Bounds::new(
 7810        Point::new(
 7811            window_size.width - corner_size.width,
 7812            window_size.height - corner_size.height,
 7813        ),
 7814        corner_size,
 7815    );
 7816    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 7817        return Some(ResizeEdge::BottomRight);
 7818    }
 7819
 7820    if !tiling.top && pos.y < shadow_size {
 7821        Some(ResizeEdge::Top)
 7822    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 7823        Some(ResizeEdge::Bottom)
 7824    } else if !tiling.left && pos.x < shadow_size {
 7825        Some(ResizeEdge::Left)
 7826    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 7827        Some(ResizeEdge::Right)
 7828    } else {
 7829        None
 7830    }
 7831}
 7832
 7833fn join_pane_into_active(
 7834    active_pane: &Entity<Pane>,
 7835    pane: &Entity<Pane>,
 7836    window: &mut Window,
 7837    cx: &mut App,
 7838) {
 7839    if pane == active_pane {
 7840    } else if pane.read(cx).items_len() == 0 {
 7841        pane.update(cx, |_, cx| {
 7842            cx.emit(pane::Event::Remove {
 7843                focus_on_pane: None,
 7844            });
 7845        })
 7846    } else {
 7847        move_all_items(pane, active_pane, window, cx);
 7848    }
 7849}
 7850
 7851fn move_all_items(
 7852    from_pane: &Entity<Pane>,
 7853    to_pane: &Entity<Pane>,
 7854    window: &mut Window,
 7855    cx: &mut App,
 7856) {
 7857    let destination_is_different = from_pane != to_pane;
 7858    let mut moved_items = 0;
 7859    for (item_ix, item_handle) in from_pane
 7860        .read(cx)
 7861        .items()
 7862        .enumerate()
 7863        .map(|(ix, item)| (ix, item.clone()))
 7864        .collect::<Vec<_>>()
 7865    {
 7866        let ix = item_ix - moved_items;
 7867        if destination_is_different {
 7868            // Close item from previous pane
 7869            from_pane.update(cx, |source, cx| {
 7870                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 7871            });
 7872            moved_items += 1;
 7873        }
 7874
 7875        // This automatically removes duplicate items in the pane
 7876        to_pane.update(cx, |destination, cx| {
 7877            destination.add_item(item_handle, true, true, None, window, cx);
 7878            window.focus(&destination.focus_handle(cx))
 7879        });
 7880    }
 7881}
 7882
 7883pub fn move_item(
 7884    source: &Entity<Pane>,
 7885    destination: &Entity<Pane>,
 7886    item_id_to_move: EntityId,
 7887    destination_index: usize,
 7888    activate: bool,
 7889    window: &mut Window,
 7890    cx: &mut App,
 7891) {
 7892    let Some((item_ix, item_handle)) = source
 7893        .read(cx)
 7894        .items()
 7895        .enumerate()
 7896        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 7897        .map(|(ix, item)| (ix, item.clone()))
 7898    else {
 7899        // Tab was closed during drag
 7900        return;
 7901    };
 7902
 7903    if source != destination {
 7904        // Close item from previous pane
 7905        source.update(cx, |source, cx| {
 7906            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 7907        });
 7908    }
 7909
 7910    // This automatically removes duplicate items in the pane
 7911    destination.update(cx, |destination, cx| {
 7912        destination.add_item_inner(
 7913            item_handle,
 7914            activate,
 7915            activate,
 7916            activate,
 7917            Some(destination_index),
 7918            window,
 7919            cx,
 7920        );
 7921        if activate {
 7922            window.focus(&destination.focus_handle(cx))
 7923        }
 7924    });
 7925}
 7926
 7927pub fn move_active_item(
 7928    source: &Entity<Pane>,
 7929    destination: &Entity<Pane>,
 7930    focus_destination: bool,
 7931    close_if_empty: bool,
 7932    window: &mut Window,
 7933    cx: &mut App,
 7934) {
 7935    if source == destination {
 7936        return;
 7937    }
 7938    let Some(active_item) = source.read(cx).active_item() else {
 7939        return;
 7940    };
 7941    source.update(cx, |source_pane, cx| {
 7942        let item_id = active_item.item_id();
 7943        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 7944        destination.update(cx, |target_pane, cx| {
 7945            target_pane.add_item(
 7946                active_item,
 7947                focus_destination,
 7948                focus_destination,
 7949                Some(target_pane.items_len()),
 7950                window,
 7951                cx,
 7952            );
 7953        });
 7954    });
 7955}
 7956
 7957pub fn clone_active_item(
 7958    workspace_id: Option<WorkspaceId>,
 7959    source: &Entity<Pane>,
 7960    destination: &Entity<Pane>,
 7961    focus_destination: bool,
 7962    window: &mut Window,
 7963    cx: &mut App,
 7964) {
 7965    if source == destination {
 7966        return;
 7967    }
 7968    let Some(active_item) = source.read(cx).active_item() else {
 7969        return;
 7970    };
 7971    destination.update(cx, |target_pane, cx| {
 7972        let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
 7973            return;
 7974        };
 7975        target_pane.add_item(
 7976            clone,
 7977            focus_destination,
 7978            focus_destination,
 7979            Some(target_pane.items_len()),
 7980            window,
 7981            cx,
 7982        );
 7983    });
 7984}
 7985
 7986#[derive(Debug)]
 7987pub struct WorkspacePosition {
 7988    pub window_bounds: Option<WindowBounds>,
 7989    pub display: Option<Uuid>,
 7990    pub centered_layout: bool,
 7991}
 7992
 7993pub fn ssh_workspace_position_from_db(
 7994    host: String,
 7995    port: Option<u16>,
 7996    user: Option<String>,
 7997    paths_to_open: &[PathBuf],
 7998    cx: &App,
 7999) -> Task<Result<WorkspacePosition>> {
 8000    let paths = paths_to_open.to_vec();
 8001
 8002    cx.background_spawn(async move {
 8003        let ssh_connection_id = persistence::DB
 8004            .get_or_create_ssh_connection(host, port, user)
 8005            .await
 8006            .context("fetching serialized ssh project")?;
 8007        let serialized_workspace =
 8008            persistence::DB.ssh_workspace_for_roots(&paths, ssh_connection_id);
 8009
 8010        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8011            (Some(WindowBounds::Windowed(bounds)), None)
 8012        } else {
 8013            let restorable_bounds = serialized_workspace
 8014                .as_ref()
 8015                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8016                .or_else(|| {
 8017                    let (display, window_bounds) = DB.last_window().log_err()?;
 8018                    Some((display?, window_bounds?))
 8019                });
 8020
 8021            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8022                (Some(serialized_status.0), Some(serialized_display))
 8023            } else {
 8024                (None, None)
 8025            }
 8026        };
 8027
 8028        let centered_layout = serialized_workspace
 8029            .as_ref()
 8030            .map(|w| w.centered_layout)
 8031            .unwrap_or(false);
 8032
 8033        Ok(WorkspacePosition {
 8034            window_bounds,
 8035            display,
 8036            centered_layout,
 8037        })
 8038    })
 8039}
 8040
 8041pub fn with_active_or_new_workspace(
 8042    cx: &mut App,
 8043    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8044) {
 8045    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8046        Some(workspace) => {
 8047            cx.defer(move |cx| {
 8048                workspace
 8049                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8050                    .log_err();
 8051            });
 8052        }
 8053        None => {
 8054            let app_state = AppState::global(cx);
 8055            if let Some(app_state) = app_state.upgrade() {
 8056                open_new(
 8057                    OpenOptions::default(),
 8058                    app_state,
 8059                    cx,
 8060                    move |workspace, window, cx| f(workspace, window, cx),
 8061                )
 8062                .detach_and_log_err(cx);
 8063            }
 8064        }
 8065    }
 8066}
 8067
 8068#[cfg(test)]
 8069mod tests {
 8070    use std::{cell::RefCell, rc::Rc};
 8071
 8072    use super::*;
 8073    use crate::{
 8074        dock::{PanelEvent, test::TestPanel},
 8075        item::{
 8076            ItemEvent,
 8077            test::{TestItem, TestProjectItem},
 8078        },
 8079    };
 8080    use fs::FakeFs;
 8081    use gpui::{
 8082        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8083        UpdateGlobal, VisualTestContext, px,
 8084    };
 8085    use project::{Project, ProjectEntryId};
 8086    use serde_json::json;
 8087    use settings::SettingsStore;
 8088
 8089    #[gpui::test]
 8090    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8091        init_test(cx);
 8092
 8093        let fs = FakeFs::new(cx.executor());
 8094        let project = Project::test(fs, [], cx).await;
 8095        let (workspace, cx) =
 8096            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8097
 8098        // Adding an item with no ambiguity renders the tab without detail.
 8099        let item1 = cx.new(|cx| {
 8100            let mut item = TestItem::new(cx);
 8101            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8102            item
 8103        });
 8104        workspace.update_in(cx, |workspace, window, cx| {
 8105            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8106        });
 8107        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8108
 8109        // Adding an item that creates ambiguity increases the level of detail on
 8110        // both tabs.
 8111        let item2 = cx.new_window_entity(|_window, cx| {
 8112            let mut item = TestItem::new(cx);
 8113            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8114            item
 8115        });
 8116        workspace.update_in(cx, |workspace, window, cx| {
 8117            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8118        });
 8119        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8120        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8121
 8122        // Adding an item that creates ambiguity increases the level of detail only
 8123        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8124        // we stop at the highest detail available.
 8125        let item3 = cx.new(|cx| {
 8126            let mut item = TestItem::new(cx);
 8127            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8128            item
 8129        });
 8130        workspace.update_in(cx, |workspace, window, cx| {
 8131            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8132        });
 8133        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8134        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8135        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8136    }
 8137
 8138    #[gpui::test]
 8139    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8140        init_test(cx);
 8141
 8142        let fs = FakeFs::new(cx.executor());
 8143        fs.insert_tree(
 8144            "/root1",
 8145            json!({
 8146                "one.txt": "",
 8147                "two.txt": "",
 8148            }),
 8149        )
 8150        .await;
 8151        fs.insert_tree(
 8152            "/root2",
 8153            json!({
 8154                "three.txt": "",
 8155            }),
 8156        )
 8157        .await;
 8158
 8159        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8160        let (workspace, cx) =
 8161            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8162        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8163        let worktree_id = project.update(cx, |project, cx| {
 8164            project.worktrees(cx).next().unwrap().read(cx).id()
 8165        });
 8166
 8167        let item1 = cx.new(|cx| {
 8168            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8169        });
 8170        let item2 = cx.new(|cx| {
 8171            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8172        });
 8173
 8174        // Add an item to an empty pane
 8175        workspace.update_in(cx, |workspace, window, cx| {
 8176            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8177        });
 8178        project.update(cx, |project, cx| {
 8179            assert_eq!(
 8180                project.active_entry(),
 8181                project
 8182                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8183                    .map(|e| e.id)
 8184            );
 8185        });
 8186        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8187
 8188        // Add a second item to a non-empty pane
 8189        workspace.update_in(cx, |workspace, window, cx| {
 8190            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8191        });
 8192        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8193        project.update(cx, |project, cx| {
 8194            assert_eq!(
 8195                project.active_entry(),
 8196                project
 8197                    .entry_for_path(&(worktree_id, "two.txt").into(), cx)
 8198                    .map(|e| e.id)
 8199            );
 8200        });
 8201
 8202        // Close the active item
 8203        pane.update_in(cx, |pane, window, cx| {
 8204            pane.close_active_item(&Default::default(), window, cx)
 8205        })
 8206        .await
 8207        .unwrap();
 8208        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8209        project.update(cx, |project, cx| {
 8210            assert_eq!(
 8211                project.active_entry(),
 8212                project
 8213                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8214                    .map(|e| e.id)
 8215            );
 8216        });
 8217
 8218        // Add a project folder
 8219        project
 8220            .update(cx, |project, cx| {
 8221                project.find_or_create_worktree("root2", true, cx)
 8222            })
 8223            .await
 8224            .unwrap();
 8225        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8226
 8227        // Remove a project folder
 8228        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8229        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8230    }
 8231
 8232    #[gpui::test]
 8233    async fn test_close_window(cx: &mut TestAppContext) {
 8234        init_test(cx);
 8235
 8236        let fs = FakeFs::new(cx.executor());
 8237        fs.insert_tree("/root", json!({ "one": "" })).await;
 8238
 8239        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8240        let (workspace, cx) =
 8241            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8242
 8243        // When there are no dirty items, there's nothing to do.
 8244        let item1 = cx.new(TestItem::new);
 8245        workspace.update_in(cx, |w, window, cx| {
 8246            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8247        });
 8248        let task = workspace.update_in(cx, |w, window, cx| {
 8249            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8250        });
 8251        assert!(task.await.unwrap());
 8252
 8253        // When there are dirty untitled items, prompt to save each one. If the user
 8254        // cancels any prompt, then abort.
 8255        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8256        let item3 = cx.new(|cx| {
 8257            TestItem::new(cx)
 8258                .with_dirty(true)
 8259                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8260        });
 8261        workspace.update_in(cx, |w, window, cx| {
 8262            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8263            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8264        });
 8265        let task = workspace.update_in(cx, |w, window, cx| {
 8266            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8267        });
 8268        cx.executor().run_until_parked();
 8269        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8270        cx.executor().run_until_parked();
 8271        assert!(!cx.has_pending_prompt());
 8272        assert!(!task.await.unwrap());
 8273    }
 8274
 8275    #[gpui::test]
 8276    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8277        init_test(cx);
 8278
 8279        // Register TestItem as a serializable item
 8280        cx.update(|cx| {
 8281            register_serializable_item::<TestItem>(cx);
 8282        });
 8283
 8284        let fs = FakeFs::new(cx.executor());
 8285        fs.insert_tree("/root", json!({ "one": "" })).await;
 8286
 8287        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8288        let (workspace, cx) =
 8289            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8290
 8291        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8292        let item1 = cx.new(|cx| {
 8293            TestItem::new(cx)
 8294                .with_dirty(true)
 8295                .with_serialize(|| Some(Task::ready(Ok(()))))
 8296        });
 8297        let item2 = cx.new(|cx| {
 8298            TestItem::new(cx)
 8299                .with_dirty(true)
 8300                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8301                .with_serialize(|| Some(Task::ready(Ok(()))))
 8302        });
 8303        workspace.update_in(cx, |w, window, cx| {
 8304            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8305            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8306        });
 8307        let task = workspace.update_in(cx, |w, window, cx| {
 8308            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8309        });
 8310        assert!(task.await.unwrap());
 8311    }
 8312
 8313    #[gpui::test]
 8314    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8315        init_test(cx);
 8316
 8317        let fs = FakeFs::new(cx.executor());
 8318
 8319        let project = Project::test(fs, None, cx).await;
 8320        let (workspace, cx) =
 8321            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8322
 8323        let item1 = cx.new(|cx| {
 8324            TestItem::new(cx)
 8325                .with_dirty(true)
 8326                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8327        });
 8328        let item2 = cx.new(|cx| {
 8329            TestItem::new(cx)
 8330                .with_dirty(true)
 8331                .with_conflict(true)
 8332                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8333        });
 8334        let item3 = cx.new(|cx| {
 8335            TestItem::new(cx)
 8336                .with_dirty(true)
 8337                .with_conflict(true)
 8338                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8339        });
 8340        let item4 = cx.new(|cx| {
 8341            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8342                let project_item = TestProjectItem::new_untitled(cx);
 8343                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8344                project_item
 8345            }])
 8346        });
 8347        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8348            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8349            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8350            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8351            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8352            workspace.active_pane().clone()
 8353        });
 8354
 8355        let close_items = pane.update_in(cx, |pane, window, cx| {
 8356            pane.activate_item(1, true, true, window, cx);
 8357            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8358            let item1_id = item1.item_id();
 8359            let item3_id = item3.item_id();
 8360            let item4_id = item4.item_id();
 8361            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8362                [item1_id, item3_id, item4_id].contains(&id)
 8363            })
 8364        });
 8365        cx.executor().run_until_parked();
 8366
 8367        assert!(cx.has_pending_prompt());
 8368        cx.simulate_prompt_answer("Save all");
 8369
 8370        cx.executor().run_until_parked();
 8371
 8372        // Item 1 is saved. There's a prompt to save item 3.
 8373        pane.update(cx, |pane, cx| {
 8374            assert_eq!(item1.read(cx).save_count, 1);
 8375            assert_eq!(item1.read(cx).save_as_count, 0);
 8376            assert_eq!(item1.read(cx).reload_count, 0);
 8377            assert_eq!(pane.items_len(), 3);
 8378            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8379        });
 8380        assert!(cx.has_pending_prompt());
 8381
 8382        // Cancel saving item 3.
 8383        cx.simulate_prompt_answer("Discard");
 8384        cx.executor().run_until_parked();
 8385
 8386        // Item 3 is reloaded. There's a prompt to save item 4.
 8387        pane.update(cx, |pane, cx| {
 8388            assert_eq!(item3.read(cx).save_count, 0);
 8389            assert_eq!(item3.read(cx).save_as_count, 0);
 8390            assert_eq!(item3.read(cx).reload_count, 1);
 8391            assert_eq!(pane.items_len(), 2);
 8392            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8393        });
 8394
 8395        // There's a prompt for a path for item 4.
 8396        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8397        close_items.await.unwrap();
 8398
 8399        // The requested items are closed.
 8400        pane.update(cx, |pane, cx| {
 8401            assert_eq!(item4.read(cx).save_count, 0);
 8402            assert_eq!(item4.read(cx).save_as_count, 1);
 8403            assert_eq!(item4.read(cx).reload_count, 0);
 8404            assert_eq!(pane.items_len(), 1);
 8405            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8406        });
 8407    }
 8408
 8409    #[gpui::test]
 8410    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8411        init_test(cx);
 8412
 8413        let fs = FakeFs::new(cx.executor());
 8414        let project = Project::test(fs, [], cx).await;
 8415        let (workspace, cx) =
 8416            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8417
 8418        // Create several workspace items with single project entries, and two
 8419        // workspace items with multiple project entries.
 8420        let single_entry_items = (0..=4)
 8421            .map(|project_entry_id| {
 8422                cx.new(|cx| {
 8423                    TestItem::new(cx)
 8424                        .with_dirty(true)
 8425                        .with_project_items(&[dirty_project_item(
 8426                            project_entry_id,
 8427                            &format!("{project_entry_id}.txt"),
 8428                            cx,
 8429                        )])
 8430                })
 8431            })
 8432            .collect::<Vec<_>>();
 8433        let item_2_3 = cx.new(|cx| {
 8434            TestItem::new(cx)
 8435                .with_dirty(true)
 8436                .with_singleton(false)
 8437                .with_project_items(&[
 8438                    single_entry_items[2].read(cx).project_items[0].clone(),
 8439                    single_entry_items[3].read(cx).project_items[0].clone(),
 8440                ])
 8441        });
 8442        let item_3_4 = cx.new(|cx| {
 8443            TestItem::new(cx)
 8444                .with_dirty(true)
 8445                .with_singleton(false)
 8446                .with_project_items(&[
 8447                    single_entry_items[3].read(cx).project_items[0].clone(),
 8448                    single_entry_items[4].read(cx).project_items[0].clone(),
 8449                ])
 8450        });
 8451
 8452        // Create two panes that contain the following project entries:
 8453        //   left pane:
 8454        //     multi-entry items:   (2, 3)
 8455        //     single-entry items:  0, 2, 3, 4
 8456        //   right pane:
 8457        //     single-entry items:  4, 1
 8458        //     multi-entry items:   (3, 4)
 8459        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8460            let left_pane = workspace.active_pane().clone();
 8461            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8462            workspace.add_item_to_active_pane(
 8463                single_entry_items[0].boxed_clone(),
 8464                None,
 8465                true,
 8466                window,
 8467                cx,
 8468            );
 8469            workspace.add_item_to_active_pane(
 8470                single_entry_items[2].boxed_clone(),
 8471                None,
 8472                true,
 8473                window,
 8474                cx,
 8475            );
 8476            workspace.add_item_to_active_pane(
 8477                single_entry_items[3].boxed_clone(),
 8478                None,
 8479                true,
 8480                window,
 8481                cx,
 8482            );
 8483            workspace.add_item_to_active_pane(
 8484                single_entry_items[4].boxed_clone(),
 8485                None,
 8486                true,
 8487                window,
 8488                cx,
 8489            );
 8490
 8491            let right_pane = workspace
 8492                .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
 8493                .unwrap();
 8494
 8495            right_pane.update(cx, |pane, cx| {
 8496                pane.add_item(
 8497                    single_entry_items[1].boxed_clone(),
 8498                    true,
 8499                    true,
 8500                    None,
 8501                    window,
 8502                    cx,
 8503                );
 8504                pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8505            });
 8506
 8507            (left_pane, right_pane)
 8508        });
 8509
 8510        cx.focus(&right_pane);
 8511
 8512        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8513            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8514                .unwrap()
 8515        });
 8516        cx.executor().run_until_parked();
 8517
 8518        let msg = cx.pending_prompt().unwrap().0;
 8519        assert!(msg.contains("1.txt"));
 8520        assert!(!msg.contains("2.txt"));
 8521        assert!(!msg.contains("3.txt"));
 8522        assert!(!msg.contains("4.txt"));
 8523
 8524        cx.simulate_prompt_answer("Cancel");
 8525        close.await;
 8526
 8527        left_pane
 8528            .update_in(cx, |left_pane, window, cx| {
 8529                left_pane.close_item_by_id(
 8530                    single_entry_items[3].entity_id(),
 8531                    SaveIntent::Skip,
 8532                    window,
 8533                    cx,
 8534                )
 8535            })
 8536            .await
 8537            .unwrap();
 8538
 8539        close = right_pane.update_in(cx, |pane, window, cx| {
 8540            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8541                .unwrap()
 8542        });
 8543        cx.executor().run_until_parked();
 8544
 8545        let details = cx.pending_prompt().unwrap().1;
 8546        assert!(details.contains("1.txt"));
 8547        assert!(!details.contains("2.txt"));
 8548        assert!(details.contains("3.txt"));
 8549        // ideally this assertion could be made, but today we can only
 8550        // save whole items not project items, so the orphaned item 3 causes
 8551        // 4 to be saved too.
 8552        // assert!(!details.contains("4.txt"));
 8553
 8554        cx.simulate_prompt_answer("Save all");
 8555
 8556        cx.executor().run_until_parked();
 8557        close.await;
 8558        right_pane.read_with(cx, |pane, _| {
 8559            assert_eq!(pane.items_len(), 0);
 8560        });
 8561    }
 8562
 8563    #[gpui::test]
 8564    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8565        init_test(cx);
 8566
 8567        let fs = FakeFs::new(cx.executor());
 8568        let project = Project::test(fs, [], cx).await;
 8569        let (workspace, cx) =
 8570            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8571        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8572
 8573        let item = cx.new(|cx| {
 8574            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8575        });
 8576        let item_id = item.entity_id();
 8577        workspace.update_in(cx, |workspace, window, cx| {
 8578            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8579        });
 8580
 8581        // Autosave on window change.
 8582        item.update(cx, |item, cx| {
 8583            SettingsStore::update_global(cx, |settings, cx| {
 8584                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8585                    settings.autosave = Some(AutosaveSetting::OnWindowChange);
 8586                })
 8587            });
 8588            item.is_dirty = true;
 8589        });
 8590
 8591        // Deactivating the window saves the file.
 8592        cx.deactivate_window();
 8593        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8594
 8595        // Re-activating the window doesn't save the file.
 8596        cx.update(|window, _| window.activate_window());
 8597        cx.executor().run_until_parked();
 8598        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8599
 8600        // Autosave on focus change.
 8601        item.update_in(cx, |item, window, cx| {
 8602            cx.focus_self(window);
 8603            SettingsStore::update_global(cx, |settings, cx| {
 8604                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8605                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8606                })
 8607            });
 8608            item.is_dirty = true;
 8609        });
 8610
 8611        // Blurring the item saves the file.
 8612        item.update_in(cx, |_, window, _| window.blur());
 8613        cx.executor().run_until_parked();
 8614        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8615
 8616        // Deactivating the window still saves the file.
 8617        item.update_in(cx, |item, window, cx| {
 8618            cx.focus_self(window);
 8619            item.is_dirty = true;
 8620        });
 8621        cx.deactivate_window();
 8622        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8623
 8624        // Autosave after delay.
 8625        item.update(cx, |item, cx| {
 8626            SettingsStore::update_global(cx, |settings, cx| {
 8627                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8628                    settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
 8629                })
 8630            });
 8631            item.is_dirty = true;
 8632            cx.emit(ItemEvent::Edit);
 8633        });
 8634
 8635        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8636        cx.executor().advance_clock(Duration::from_millis(250));
 8637        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8638
 8639        // After delay expires, the file is saved.
 8640        cx.executor().advance_clock(Duration::from_millis(250));
 8641        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8642
 8643        // Autosave on focus change, ensuring closing the tab counts as such.
 8644        item.update(cx, |item, cx| {
 8645            SettingsStore::update_global(cx, |settings, cx| {
 8646                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8647                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8648                })
 8649            });
 8650            item.is_dirty = true;
 8651            for project_item in &mut item.project_items {
 8652                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8653            }
 8654        });
 8655
 8656        pane.update_in(cx, |pane, window, cx| {
 8657            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8658        })
 8659        .await
 8660        .unwrap();
 8661        assert!(!cx.has_pending_prompt());
 8662        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8663
 8664        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8665        workspace.update_in(cx, |workspace, window, cx| {
 8666            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8667        });
 8668        item.update_in(cx, |item, window, cx| {
 8669            item.project_items[0].update(cx, |item, _| {
 8670                item.entry_id = None;
 8671            });
 8672            item.is_dirty = true;
 8673            window.blur();
 8674        });
 8675        cx.run_until_parked();
 8676        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8677
 8678        // Ensure autosave is prevented for deleted files also when closing the buffer.
 8679        let _close_items = pane.update_in(cx, |pane, window, cx| {
 8680            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8681        });
 8682        cx.run_until_parked();
 8683        assert!(cx.has_pending_prompt());
 8684        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8685    }
 8686
 8687    #[gpui::test]
 8688    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 8689        init_test(cx);
 8690
 8691        let fs = FakeFs::new(cx.executor());
 8692
 8693        let project = Project::test(fs, [], cx).await;
 8694        let (workspace, cx) =
 8695            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8696
 8697        let item = cx.new(|cx| {
 8698            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8699        });
 8700        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8701        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 8702        let toolbar_notify_count = Rc::new(RefCell::new(0));
 8703
 8704        workspace.update_in(cx, |workspace, window, cx| {
 8705            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8706            let toolbar_notification_count = toolbar_notify_count.clone();
 8707            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 8708                *toolbar_notification_count.borrow_mut() += 1
 8709            })
 8710            .detach();
 8711        });
 8712
 8713        pane.read_with(cx, |pane, _| {
 8714            assert!(!pane.can_navigate_backward());
 8715            assert!(!pane.can_navigate_forward());
 8716        });
 8717
 8718        item.update_in(cx, |item, _, cx| {
 8719            item.set_state("one".to_string(), cx);
 8720        });
 8721
 8722        // Toolbar must be notified to re-render the navigation buttons
 8723        assert_eq!(*toolbar_notify_count.borrow(), 1);
 8724
 8725        pane.read_with(cx, |pane, _| {
 8726            assert!(pane.can_navigate_backward());
 8727            assert!(!pane.can_navigate_forward());
 8728        });
 8729
 8730        workspace
 8731            .update_in(cx, |workspace, window, cx| {
 8732                workspace.go_back(pane.downgrade(), window, cx)
 8733            })
 8734            .await
 8735            .unwrap();
 8736
 8737        assert_eq!(*toolbar_notify_count.borrow(), 2);
 8738        pane.read_with(cx, |pane, _| {
 8739            assert!(!pane.can_navigate_backward());
 8740            assert!(pane.can_navigate_forward());
 8741        });
 8742    }
 8743
 8744    #[gpui::test]
 8745    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 8746        init_test(cx);
 8747        let fs = FakeFs::new(cx.executor());
 8748
 8749        let project = Project::test(fs, [], cx).await;
 8750        let (workspace, cx) =
 8751            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8752
 8753        let panel = workspace.update_in(cx, |workspace, window, cx| {
 8754            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 8755            workspace.add_panel(panel.clone(), window, cx);
 8756
 8757            workspace
 8758                .right_dock()
 8759                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 8760
 8761            panel
 8762        });
 8763
 8764        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8765        pane.update_in(cx, |pane, window, cx| {
 8766            let item = cx.new(TestItem::new);
 8767            pane.add_item(Box::new(item), true, true, None, window, cx);
 8768        });
 8769
 8770        // Transfer focus from center to panel
 8771        workspace.update_in(cx, |workspace, window, cx| {
 8772            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8773        });
 8774
 8775        workspace.update_in(cx, |workspace, window, cx| {
 8776            assert!(workspace.right_dock().read(cx).is_open());
 8777            assert!(!panel.is_zoomed(window, cx));
 8778            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8779        });
 8780
 8781        // Transfer focus from panel to center
 8782        workspace.update_in(cx, |workspace, window, cx| {
 8783            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8784        });
 8785
 8786        workspace.update_in(cx, |workspace, window, cx| {
 8787            assert!(workspace.right_dock().read(cx).is_open());
 8788            assert!(!panel.is_zoomed(window, cx));
 8789            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8790        });
 8791
 8792        // Close the dock
 8793        workspace.update_in(cx, |workspace, window, cx| {
 8794            workspace.toggle_dock(DockPosition::Right, window, cx);
 8795        });
 8796
 8797        workspace.update_in(cx, |workspace, window, cx| {
 8798            assert!(!workspace.right_dock().read(cx).is_open());
 8799            assert!(!panel.is_zoomed(window, cx));
 8800            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8801        });
 8802
 8803        // Open the dock
 8804        workspace.update_in(cx, |workspace, window, cx| {
 8805            workspace.toggle_dock(DockPosition::Right, window, cx);
 8806        });
 8807
 8808        workspace.update_in(cx, |workspace, window, cx| {
 8809            assert!(workspace.right_dock().read(cx).is_open());
 8810            assert!(!panel.is_zoomed(window, cx));
 8811            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8812        });
 8813
 8814        // Focus and zoom panel
 8815        panel.update_in(cx, |panel, window, cx| {
 8816            cx.focus_self(window);
 8817            panel.set_zoomed(true, window, cx)
 8818        });
 8819
 8820        workspace.update_in(cx, |workspace, window, cx| {
 8821            assert!(workspace.right_dock().read(cx).is_open());
 8822            assert!(panel.is_zoomed(window, cx));
 8823            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8824        });
 8825
 8826        // Transfer focus to the center closes the dock
 8827        workspace.update_in(cx, |workspace, window, cx| {
 8828            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8829        });
 8830
 8831        workspace.update_in(cx, |workspace, window, cx| {
 8832            assert!(!workspace.right_dock().read(cx).is_open());
 8833            assert!(panel.is_zoomed(window, cx));
 8834            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8835        });
 8836
 8837        // Transferring focus back to the panel keeps it zoomed
 8838        workspace.update_in(cx, |workspace, window, cx| {
 8839            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8840        });
 8841
 8842        workspace.update_in(cx, |workspace, window, cx| {
 8843            assert!(workspace.right_dock().read(cx).is_open());
 8844            assert!(panel.is_zoomed(window, cx));
 8845            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8846        });
 8847
 8848        // Close the dock while it is zoomed
 8849        workspace.update_in(cx, |workspace, window, cx| {
 8850            workspace.toggle_dock(DockPosition::Right, window, cx)
 8851        });
 8852
 8853        workspace.update_in(cx, |workspace, window, cx| {
 8854            assert!(!workspace.right_dock().read(cx).is_open());
 8855            assert!(panel.is_zoomed(window, cx));
 8856            assert!(workspace.zoomed.is_none());
 8857            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8858        });
 8859
 8860        // Opening the dock, when it's zoomed, retains focus
 8861        workspace.update_in(cx, |workspace, window, cx| {
 8862            workspace.toggle_dock(DockPosition::Right, window, cx)
 8863        });
 8864
 8865        workspace.update_in(cx, |workspace, window, cx| {
 8866            assert!(workspace.right_dock().read(cx).is_open());
 8867            assert!(panel.is_zoomed(window, cx));
 8868            assert!(workspace.zoomed.is_some());
 8869            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8870        });
 8871
 8872        // Unzoom and close the panel, zoom the active pane.
 8873        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 8874        workspace.update_in(cx, |workspace, window, cx| {
 8875            workspace.toggle_dock(DockPosition::Right, window, cx)
 8876        });
 8877        pane.update_in(cx, |pane, window, cx| {
 8878            pane.toggle_zoom(&Default::default(), window, cx)
 8879        });
 8880
 8881        // Opening a dock unzooms the pane.
 8882        workspace.update_in(cx, |workspace, window, cx| {
 8883            workspace.toggle_dock(DockPosition::Right, window, cx)
 8884        });
 8885        workspace.update_in(cx, |workspace, window, cx| {
 8886            let pane = pane.read(cx);
 8887            assert!(!pane.is_zoomed());
 8888            assert!(!pane.focus_handle(cx).is_focused(window));
 8889            assert!(workspace.right_dock().read(cx).is_open());
 8890            assert!(workspace.zoomed.is_none());
 8891        });
 8892    }
 8893
 8894    #[gpui::test]
 8895    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 8896        init_test(cx);
 8897
 8898        let fs = FakeFs::new(cx.executor());
 8899
 8900        let project = Project::test(fs, None, cx).await;
 8901        let (workspace, cx) =
 8902            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8903
 8904        // Let's arrange the panes like this:
 8905        //
 8906        // +-----------------------+
 8907        // |         top           |
 8908        // +------+--------+-------+
 8909        // | left | center | right |
 8910        // +------+--------+-------+
 8911        // |        bottom         |
 8912        // +-----------------------+
 8913
 8914        let top_item = cx.new(|cx| {
 8915            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 8916        });
 8917        let bottom_item = cx.new(|cx| {
 8918            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 8919        });
 8920        let left_item = cx.new(|cx| {
 8921            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 8922        });
 8923        let right_item = cx.new(|cx| {
 8924            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 8925        });
 8926        let center_item = cx.new(|cx| {
 8927            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 8928        });
 8929
 8930        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8931            let top_pane_id = workspace.active_pane().entity_id();
 8932            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 8933            workspace.split_pane(
 8934                workspace.active_pane().clone(),
 8935                SplitDirection::Down,
 8936                window,
 8937                cx,
 8938            );
 8939            top_pane_id
 8940        });
 8941        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8942            let bottom_pane_id = workspace.active_pane().entity_id();
 8943            workspace.add_item_to_active_pane(
 8944                Box::new(bottom_item.clone()),
 8945                None,
 8946                false,
 8947                window,
 8948                cx,
 8949            );
 8950            workspace.split_pane(
 8951                workspace.active_pane().clone(),
 8952                SplitDirection::Up,
 8953                window,
 8954                cx,
 8955            );
 8956            bottom_pane_id
 8957        });
 8958        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8959            let left_pane_id = workspace.active_pane().entity_id();
 8960            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 8961            workspace.split_pane(
 8962                workspace.active_pane().clone(),
 8963                SplitDirection::Right,
 8964                window,
 8965                cx,
 8966            );
 8967            left_pane_id
 8968        });
 8969        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8970            let right_pane_id = workspace.active_pane().entity_id();
 8971            workspace.add_item_to_active_pane(
 8972                Box::new(right_item.clone()),
 8973                None,
 8974                false,
 8975                window,
 8976                cx,
 8977            );
 8978            workspace.split_pane(
 8979                workspace.active_pane().clone(),
 8980                SplitDirection::Left,
 8981                window,
 8982                cx,
 8983            );
 8984            right_pane_id
 8985        });
 8986        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8987            let center_pane_id = workspace.active_pane().entity_id();
 8988            workspace.add_item_to_active_pane(
 8989                Box::new(center_item.clone()),
 8990                None,
 8991                false,
 8992                window,
 8993                cx,
 8994            );
 8995            center_pane_id
 8996        });
 8997        cx.executor().run_until_parked();
 8998
 8999        workspace.update_in(cx, |workspace, window, cx| {
 9000            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9001
 9002            // Join into next from center pane into right
 9003            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9004        });
 9005
 9006        workspace.update_in(cx, |workspace, window, cx| {
 9007            let active_pane = workspace.active_pane();
 9008            assert_eq!(right_pane_id, active_pane.entity_id());
 9009            assert_eq!(2, active_pane.read(cx).items_len());
 9010            let item_ids_in_pane =
 9011                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9012            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9013            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9014
 9015            // Join into next from right pane into bottom
 9016            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9017        });
 9018
 9019        workspace.update_in(cx, |workspace, window, cx| {
 9020            let active_pane = workspace.active_pane();
 9021            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9022            assert_eq!(3, active_pane.read(cx).items_len());
 9023            let item_ids_in_pane =
 9024                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9025            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9026            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9027            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9028
 9029            // Join into next from bottom pane into left
 9030            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9031        });
 9032
 9033        workspace.update_in(cx, |workspace, window, cx| {
 9034            let active_pane = workspace.active_pane();
 9035            assert_eq!(left_pane_id, active_pane.entity_id());
 9036            assert_eq!(4, active_pane.read(cx).items_len());
 9037            let item_ids_in_pane =
 9038                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9039            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9040            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9041            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9042            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9043
 9044            // Join into next from left pane into top
 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!(top_pane_id, active_pane.entity_id());
 9051            assert_eq!(5, 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            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9059
 9060            // Single pane left: no-op
 9061            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9062        });
 9063
 9064        workspace.update(cx, |workspace, _cx| {
 9065            let active_pane = workspace.active_pane();
 9066            assert_eq!(top_pane_id, active_pane.entity_id());
 9067        });
 9068    }
 9069
 9070    fn add_an_item_to_active_pane(
 9071        cx: &mut VisualTestContext,
 9072        workspace: &Entity<Workspace>,
 9073        item_id: u64,
 9074    ) -> Entity<TestItem> {
 9075        let item = cx.new(|cx| {
 9076            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9077                item_id,
 9078                "item{item_id}.txt",
 9079                cx,
 9080            )])
 9081        });
 9082        workspace.update_in(cx, |workspace, window, cx| {
 9083            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9084        });
 9085        item
 9086    }
 9087
 9088    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9089        workspace.update_in(cx, |workspace, window, cx| {
 9090            workspace.split_pane(
 9091                workspace.active_pane().clone(),
 9092                SplitDirection::Right,
 9093                window,
 9094                cx,
 9095            )
 9096        })
 9097    }
 9098
 9099    #[gpui::test]
 9100    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9101        init_test(cx);
 9102        let fs = FakeFs::new(cx.executor());
 9103        let project = Project::test(fs, None, cx).await;
 9104        let (workspace, cx) =
 9105            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9106
 9107        add_an_item_to_active_pane(cx, &workspace, 1);
 9108        split_pane(cx, &workspace);
 9109        add_an_item_to_active_pane(cx, &workspace, 2);
 9110        split_pane(cx, &workspace); // empty pane
 9111        split_pane(cx, &workspace);
 9112        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9113
 9114        cx.executor().run_until_parked();
 9115
 9116        workspace.update(cx, |workspace, cx| {
 9117            let num_panes = workspace.panes().len();
 9118            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9119            let active_item = workspace
 9120                .active_pane()
 9121                .read(cx)
 9122                .active_item()
 9123                .expect("item is in focus");
 9124
 9125            assert_eq!(num_panes, 4);
 9126            assert_eq!(num_items_in_current_pane, 1);
 9127            assert_eq!(active_item.item_id(), last_item.item_id());
 9128        });
 9129
 9130        workspace.update_in(cx, |workspace, window, cx| {
 9131            workspace.join_all_panes(window, cx);
 9132        });
 9133
 9134        workspace.update(cx, |workspace, cx| {
 9135            let num_panes = workspace.panes().len();
 9136            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9137            let active_item = workspace
 9138                .active_pane()
 9139                .read(cx)
 9140                .active_item()
 9141                .expect("item is in focus");
 9142
 9143            assert_eq!(num_panes, 1);
 9144            assert_eq!(num_items_in_current_pane, 3);
 9145            assert_eq!(active_item.item_id(), last_item.item_id());
 9146        });
 9147    }
 9148    struct TestModal(FocusHandle);
 9149
 9150    impl TestModal {
 9151        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9152            Self(cx.focus_handle())
 9153        }
 9154    }
 9155
 9156    impl EventEmitter<DismissEvent> for TestModal {}
 9157
 9158    impl Focusable for TestModal {
 9159        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9160            self.0.clone()
 9161        }
 9162    }
 9163
 9164    impl ModalView for TestModal {}
 9165
 9166    impl Render for TestModal {
 9167        fn render(
 9168            &mut self,
 9169            _window: &mut Window,
 9170            _cx: &mut Context<TestModal>,
 9171        ) -> impl IntoElement {
 9172            div().track_focus(&self.0)
 9173        }
 9174    }
 9175
 9176    #[gpui::test]
 9177    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9178        init_test(cx);
 9179        let fs = FakeFs::new(cx.executor());
 9180
 9181        let project = Project::test(fs, [], cx).await;
 9182        let (workspace, cx) =
 9183            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9184
 9185        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9186            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9187            workspace.add_panel(panel_1.clone(), window, cx);
 9188            workspace.toggle_dock(DockPosition::Left, window, cx);
 9189            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9190            workspace.add_panel(panel_2.clone(), window, cx);
 9191            workspace.toggle_dock(DockPosition::Right, window, cx);
 9192
 9193            let left_dock = workspace.left_dock();
 9194            assert_eq!(
 9195                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9196                panel_1.panel_id()
 9197            );
 9198            assert_eq!(
 9199                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9200                panel_1.size(window, cx)
 9201            );
 9202
 9203            left_dock.update(cx, |left_dock, cx| {
 9204                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9205            });
 9206            assert_eq!(
 9207                workspace
 9208                    .right_dock()
 9209                    .read(cx)
 9210                    .visible_panel()
 9211                    .unwrap()
 9212                    .panel_id(),
 9213                panel_2.panel_id(),
 9214            );
 9215
 9216            (panel_1, panel_2)
 9217        });
 9218
 9219        // Move panel_1 to the right
 9220        panel_1.update_in(cx, |panel_1, window, cx| {
 9221            panel_1.set_position(DockPosition::Right, window, cx)
 9222        });
 9223
 9224        workspace.update_in(cx, |workspace, window, cx| {
 9225            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9226            // Since it was the only panel on the left, the left dock should now be closed.
 9227            assert!(!workspace.left_dock().read(cx).is_open());
 9228            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9229            let right_dock = workspace.right_dock();
 9230            assert_eq!(
 9231                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9232                panel_1.panel_id()
 9233            );
 9234            assert_eq!(
 9235                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9236                px(1337.)
 9237            );
 9238
 9239            // Now we move panel_2 to the left
 9240            panel_2.set_position(DockPosition::Left, window, cx);
 9241        });
 9242
 9243        workspace.update(cx, |workspace, cx| {
 9244            // Since panel_2 was not visible on the right, we don't open the left dock.
 9245            assert!(!workspace.left_dock().read(cx).is_open());
 9246            // And the right dock is unaffected in its displaying of panel_1
 9247            assert!(workspace.right_dock().read(cx).is_open());
 9248            assert_eq!(
 9249                workspace
 9250                    .right_dock()
 9251                    .read(cx)
 9252                    .visible_panel()
 9253                    .unwrap()
 9254                    .panel_id(),
 9255                panel_1.panel_id(),
 9256            );
 9257        });
 9258
 9259        // Move panel_1 back to the left
 9260        panel_1.update_in(cx, |panel_1, window, cx| {
 9261            panel_1.set_position(DockPosition::Left, window, cx)
 9262        });
 9263
 9264        workspace.update_in(cx, |workspace, window, cx| {
 9265            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9266            let left_dock = workspace.left_dock();
 9267            assert!(left_dock.read(cx).is_open());
 9268            assert_eq!(
 9269                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9270                panel_1.panel_id()
 9271            );
 9272            assert_eq!(
 9273                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9274                px(1337.)
 9275            );
 9276            // And the right dock should be closed as it no longer has any panels.
 9277            assert!(!workspace.right_dock().read(cx).is_open());
 9278
 9279            // Now we move panel_1 to the bottom
 9280            panel_1.set_position(DockPosition::Bottom, window, cx);
 9281        });
 9282
 9283        workspace.update_in(cx, |workspace, window, cx| {
 9284            // Since panel_1 was visible on the left, we close the left dock.
 9285            assert!(!workspace.left_dock().read(cx).is_open());
 9286            // The bottom dock is sized based on the panel's default size,
 9287            // since the panel orientation changed from vertical to horizontal.
 9288            let bottom_dock = workspace.bottom_dock();
 9289            assert_eq!(
 9290                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9291                panel_1.size(window, cx),
 9292            );
 9293            // Close bottom dock and move panel_1 back to the left.
 9294            bottom_dock.update(cx, |bottom_dock, cx| {
 9295                bottom_dock.set_open(false, window, cx)
 9296            });
 9297            panel_1.set_position(DockPosition::Left, window, cx);
 9298        });
 9299
 9300        // Emit activated event on panel 1
 9301        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9302
 9303        // Now the left dock is open and panel_1 is active and focused.
 9304        workspace.update_in(cx, |workspace, window, cx| {
 9305            let left_dock = workspace.left_dock();
 9306            assert!(left_dock.read(cx).is_open());
 9307            assert_eq!(
 9308                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9309                panel_1.panel_id(),
 9310            );
 9311            assert!(panel_1.focus_handle(cx).is_focused(window));
 9312        });
 9313
 9314        // Emit closed event on panel 2, which is not active
 9315        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9316
 9317        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9318        workspace.update(cx, |workspace, cx| {
 9319            let left_dock = workspace.left_dock();
 9320            assert!(left_dock.read(cx).is_open());
 9321            assert_eq!(
 9322                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9323                panel_1.panel_id(),
 9324            );
 9325        });
 9326
 9327        // Emitting a ZoomIn event shows the panel as zoomed.
 9328        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9329        workspace.read_with(cx, |workspace, _| {
 9330            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9331            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9332        });
 9333
 9334        // Move panel to another dock while it is zoomed
 9335        panel_1.update_in(cx, |panel, window, cx| {
 9336            panel.set_position(DockPosition::Right, window, cx)
 9337        });
 9338        workspace.read_with(cx, |workspace, _| {
 9339            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9340
 9341            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9342        });
 9343
 9344        // This is a helper for getting a:
 9345        // - valid focus on an element,
 9346        // - that isn't a part of the panes and panels system of the Workspace,
 9347        // - and doesn't trigger the 'on_focus_lost' API.
 9348        let focus_other_view = {
 9349            let workspace = workspace.clone();
 9350            move |cx: &mut VisualTestContext| {
 9351                workspace.update_in(cx, |workspace, window, cx| {
 9352                    if workspace.active_modal::<TestModal>(cx).is_some() {
 9353                        workspace.toggle_modal(window, cx, TestModal::new);
 9354                        workspace.toggle_modal(window, cx, TestModal::new);
 9355                    } else {
 9356                        workspace.toggle_modal(window, cx, TestModal::new);
 9357                    }
 9358                })
 9359            }
 9360        };
 9361
 9362        // If focus is transferred to another view that's not a panel or another pane, we still show
 9363        // the panel as zoomed.
 9364        focus_other_view(cx);
 9365        workspace.read_with(cx, |workspace, _| {
 9366            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9367            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9368        });
 9369
 9370        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9371        workspace.update_in(cx, |_workspace, window, cx| {
 9372            cx.focus_self(window);
 9373        });
 9374        workspace.read_with(cx, |workspace, _| {
 9375            assert_eq!(workspace.zoomed, None);
 9376            assert_eq!(workspace.zoomed_position, None);
 9377        });
 9378
 9379        // If focus is transferred again to another view that's not a panel or a pane, we won't
 9380        // show the panel as zoomed because it wasn't zoomed before.
 9381        focus_other_view(cx);
 9382        workspace.read_with(cx, |workspace, _| {
 9383            assert_eq!(workspace.zoomed, None);
 9384            assert_eq!(workspace.zoomed_position, None);
 9385        });
 9386
 9387        // When the panel is activated, it is zoomed again.
 9388        cx.dispatch_action(ToggleRightDock);
 9389        workspace.read_with(cx, |workspace, _| {
 9390            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9391            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9392        });
 9393
 9394        // Emitting a ZoomOut event unzooms the panel.
 9395        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
 9396        workspace.read_with(cx, |workspace, _| {
 9397            assert_eq!(workspace.zoomed, None);
 9398            assert_eq!(workspace.zoomed_position, None);
 9399        });
 9400
 9401        // Emit closed event on panel 1, which is active
 9402        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9403
 9404        // Now the left dock is closed, because panel_1 was the active panel
 9405        workspace.update(cx, |workspace, cx| {
 9406            let right_dock = workspace.right_dock();
 9407            assert!(!right_dock.read(cx).is_open());
 9408        });
 9409    }
 9410
 9411    #[gpui::test]
 9412    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
 9413        init_test(cx);
 9414
 9415        let fs = FakeFs::new(cx.background_executor.clone());
 9416        let project = Project::test(fs, [], cx).await;
 9417        let (workspace, cx) =
 9418            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9419        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9420
 9421        let dirty_regular_buffer = cx.new(|cx| {
 9422            TestItem::new(cx)
 9423                .with_dirty(true)
 9424                .with_label("1.txt")
 9425                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9426        });
 9427        let dirty_regular_buffer_2 = cx.new(|cx| {
 9428            TestItem::new(cx)
 9429                .with_dirty(true)
 9430                .with_label("2.txt")
 9431                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9432        });
 9433        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9434            TestItem::new(cx)
 9435                .with_dirty(true)
 9436                .with_singleton(false)
 9437                .with_label("Fake Project Search")
 9438                .with_project_items(&[
 9439                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9440                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9441                ])
 9442        });
 9443        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9444        workspace.update_in(cx, |workspace, window, cx| {
 9445            workspace.add_item(
 9446                pane.clone(),
 9447                Box::new(dirty_regular_buffer.clone()),
 9448                None,
 9449                false,
 9450                false,
 9451                window,
 9452                cx,
 9453            );
 9454            workspace.add_item(
 9455                pane.clone(),
 9456                Box::new(dirty_regular_buffer_2.clone()),
 9457                None,
 9458                false,
 9459                false,
 9460                window,
 9461                cx,
 9462            );
 9463            workspace.add_item(
 9464                pane.clone(),
 9465                Box::new(dirty_multi_buffer_with_both.clone()),
 9466                None,
 9467                false,
 9468                false,
 9469                window,
 9470                cx,
 9471            );
 9472        });
 9473
 9474        pane.update_in(cx, |pane, window, cx| {
 9475            pane.activate_item(2, true, true, window, cx);
 9476            assert_eq!(
 9477                pane.active_item().unwrap().item_id(),
 9478                multi_buffer_with_both_files_id,
 9479                "Should select the multi buffer in the pane"
 9480            );
 9481        });
 9482        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9483            pane.close_other_items(
 9484                &CloseOtherItems {
 9485                    save_intent: Some(SaveIntent::Save),
 9486                    close_pinned: true,
 9487                },
 9488                None,
 9489                window,
 9490                cx,
 9491            )
 9492        });
 9493        cx.background_executor.run_until_parked();
 9494        assert!(!cx.has_pending_prompt());
 9495        close_all_but_multi_buffer_task
 9496            .await
 9497            .expect("Closing all buffers but the multi buffer failed");
 9498        pane.update(cx, |pane, cx| {
 9499            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9500            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9501            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9502            assert_eq!(pane.items_len(), 1);
 9503            assert_eq!(
 9504                pane.active_item().unwrap().item_id(),
 9505                multi_buffer_with_both_files_id,
 9506                "Should have only the multi buffer left in the pane"
 9507            );
 9508            assert!(
 9509                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9510                "The multi buffer containing the unsaved buffer should still be dirty"
 9511            );
 9512        });
 9513
 9514        dirty_regular_buffer.update(cx, |buffer, cx| {
 9515            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9516        });
 9517
 9518        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9519            pane.close_active_item(
 9520                &CloseActiveItem {
 9521                    save_intent: Some(SaveIntent::Close),
 9522                    close_pinned: false,
 9523                },
 9524                window,
 9525                cx,
 9526            )
 9527        });
 9528        cx.background_executor.run_until_parked();
 9529        assert!(
 9530            cx.has_pending_prompt(),
 9531            "Dirty multi buffer should prompt a save dialog"
 9532        );
 9533        cx.simulate_prompt_answer("Save");
 9534        cx.background_executor.run_until_parked();
 9535        close_multi_buffer_task
 9536            .await
 9537            .expect("Closing the multi buffer failed");
 9538        pane.update(cx, |pane, cx| {
 9539            assert_eq!(
 9540                dirty_multi_buffer_with_both.read(cx).save_count,
 9541                1,
 9542                "Multi buffer item should get be saved"
 9543            );
 9544            // Test impl does not save inner items, so we do not assert them
 9545            assert_eq!(
 9546                pane.items_len(),
 9547                0,
 9548                "No more items should be left in the pane"
 9549            );
 9550            assert!(pane.active_item().is_none());
 9551        });
 9552    }
 9553
 9554    #[gpui::test]
 9555    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9556        cx: &mut TestAppContext,
 9557    ) {
 9558        init_test(cx);
 9559
 9560        let fs = FakeFs::new(cx.background_executor.clone());
 9561        let project = Project::test(fs, [], cx).await;
 9562        let (workspace, cx) =
 9563            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9564        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9565
 9566        let dirty_regular_buffer = cx.new(|cx| {
 9567            TestItem::new(cx)
 9568                .with_dirty(true)
 9569                .with_label("1.txt")
 9570                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9571        });
 9572        let dirty_regular_buffer_2 = cx.new(|cx| {
 9573            TestItem::new(cx)
 9574                .with_dirty(true)
 9575                .with_label("2.txt")
 9576                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9577        });
 9578        let clear_regular_buffer = cx.new(|cx| {
 9579            TestItem::new(cx)
 9580                .with_label("3.txt")
 9581                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9582        });
 9583
 9584        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9585            TestItem::new(cx)
 9586                .with_dirty(true)
 9587                .with_singleton(false)
 9588                .with_label("Fake Project Search")
 9589                .with_project_items(&[
 9590                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9591                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9592                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9593                ])
 9594        });
 9595        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9596        workspace.update_in(cx, |workspace, window, cx| {
 9597            workspace.add_item(
 9598                pane.clone(),
 9599                Box::new(dirty_regular_buffer.clone()),
 9600                None,
 9601                false,
 9602                false,
 9603                window,
 9604                cx,
 9605            );
 9606            workspace.add_item(
 9607                pane.clone(),
 9608                Box::new(dirty_multi_buffer_with_both.clone()),
 9609                None,
 9610                false,
 9611                false,
 9612                window,
 9613                cx,
 9614            );
 9615        });
 9616
 9617        pane.update_in(cx, |pane, window, cx| {
 9618            pane.activate_item(1, true, true, window, cx);
 9619            assert_eq!(
 9620                pane.active_item().unwrap().item_id(),
 9621                multi_buffer_with_both_files_id,
 9622                "Should select the multi buffer in the pane"
 9623            );
 9624        });
 9625        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9626            pane.close_active_item(
 9627                &CloseActiveItem {
 9628                    save_intent: None,
 9629                    close_pinned: false,
 9630                },
 9631                window,
 9632                cx,
 9633            )
 9634        });
 9635        cx.background_executor.run_until_parked();
 9636        assert!(
 9637            cx.has_pending_prompt(),
 9638            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9639        );
 9640    }
 9641
 9642    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9643    /// closed when they are deleted from disk.
 9644    #[gpui::test]
 9645    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9646        init_test(cx);
 9647
 9648        // Enable the close_on_disk_deletion setting
 9649        cx.update_global(|store: &mut SettingsStore, cx| {
 9650            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9651                settings.close_on_file_delete = Some(true);
 9652            });
 9653        });
 9654
 9655        let fs = FakeFs::new(cx.background_executor.clone());
 9656        let project = Project::test(fs, [], cx).await;
 9657        let (workspace, cx) =
 9658            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9659        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9660
 9661        // Create a test item that simulates a file
 9662        let item = cx.new(|cx| {
 9663            TestItem::new(cx)
 9664                .with_label("test.txt")
 9665                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9666        });
 9667
 9668        // Add item to workspace
 9669        workspace.update_in(cx, |workspace, window, cx| {
 9670            workspace.add_item(
 9671                pane.clone(),
 9672                Box::new(item.clone()),
 9673                None,
 9674                false,
 9675                false,
 9676                window,
 9677                cx,
 9678            );
 9679        });
 9680
 9681        // Verify the item is in the pane
 9682        pane.read_with(cx, |pane, _| {
 9683            assert_eq!(pane.items().count(), 1);
 9684        });
 9685
 9686        // Simulate file deletion by setting the item's deleted state
 9687        item.update(cx, |item, _| {
 9688            item.set_has_deleted_file(true);
 9689        });
 9690
 9691        // Emit UpdateTab event to trigger the close behavior
 9692        cx.run_until_parked();
 9693        item.update(cx, |_, cx| {
 9694            cx.emit(ItemEvent::UpdateTab);
 9695        });
 9696
 9697        // Allow the close operation to complete
 9698        cx.run_until_parked();
 9699
 9700        // Verify the item was automatically closed
 9701        pane.read_with(cx, |pane, _| {
 9702            assert_eq!(
 9703                pane.items().count(),
 9704                0,
 9705                "Item should be automatically closed when file is deleted"
 9706            );
 9707        });
 9708    }
 9709
 9710    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9711    /// open with a strikethrough when they are deleted from disk.
 9712    #[gpui::test]
 9713    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9714        init_test(cx);
 9715
 9716        // Ensure close_on_disk_deletion is disabled (default)
 9717        cx.update_global(|store: &mut SettingsStore, cx| {
 9718            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9719                settings.close_on_file_delete = Some(false);
 9720            });
 9721        });
 9722
 9723        let fs = FakeFs::new(cx.background_executor.clone());
 9724        let project = Project::test(fs, [], cx).await;
 9725        let (workspace, cx) =
 9726            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9727        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9728
 9729        // Create a test item that simulates a file
 9730        let item = cx.new(|cx| {
 9731            TestItem::new(cx)
 9732                .with_label("test.txt")
 9733                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9734        });
 9735
 9736        // Add item to workspace
 9737        workspace.update_in(cx, |workspace, window, cx| {
 9738            workspace.add_item(
 9739                pane.clone(),
 9740                Box::new(item.clone()),
 9741                None,
 9742                false,
 9743                false,
 9744                window,
 9745                cx,
 9746            );
 9747        });
 9748
 9749        // Verify the item is in the pane
 9750        pane.read_with(cx, |pane, _| {
 9751            assert_eq!(pane.items().count(), 1);
 9752        });
 9753
 9754        // Simulate file deletion
 9755        item.update(cx, |item, _| {
 9756            item.set_has_deleted_file(true);
 9757        });
 9758
 9759        // Emit UpdateTab event
 9760        cx.run_until_parked();
 9761        item.update(cx, |_, cx| {
 9762            cx.emit(ItemEvent::UpdateTab);
 9763        });
 9764
 9765        // Allow any potential close operation to complete
 9766        cx.run_until_parked();
 9767
 9768        // Verify the item remains open (with strikethrough)
 9769        pane.read_with(cx, |pane, _| {
 9770            assert_eq!(
 9771                pane.items().count(),
 9772                1,
 9773                "Item should remain open when close_on_disk_deletion is disabled"
 9774            );
 9775        });
 9776
 9777        // Verify the item shows as deleted
 9778        item.read_with(cx, |item, _| {
 9779            assert!(
 9780                item.has_deleted_file,
 9781                "Item should be marked as having deleted file"
 9782            );
 9783        });
 9784    }
 9785
 9786    /// Tests that dirty files are not automatically closed when deleted from disk,
 9787    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
 9788    /// unsaved changes without being prompted.
 9789    #[gpui::test]
 9790    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
 9791        init_test(cx);
 9792
 9793        // Enable the close_on_file_delete setting
 9794        cx.update_global(|store: &mut SettingsStore, cx| {
 9795            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9796                settings.close_on_file_delete = Some(true);
 9797            });
 9798        });
 9799
 9800        let fs = FakeFs::new(cx.background_executor.clone());
 9801        let project = Project::test(fs, [], cx).await;
 9802        let (workspace, cx) =
 9803            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9804        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9805
 9806        // Create a dirty test item
 9807        let item = cx.new(|cx| {
 9808            TestItem::new(cx)
 9809                .with_dirty(true)
 9810                .with_label("test.txt")
 9811                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9812        });
 9813
 9814        // Add item to workspace
 9815        workspace.update_in(cx, |workspace, window, cx| {
 9816            workspace.add_item(
 9817                pane.clone(),
 9818                Box::new(item.clone()),
 9819                None,
 9820                false,
 9821                false,
 9822                window,
 9823                cx,
 9824            );
 9825        });
 9826
 9827        // Simulate file deletion
 9828        item.update(cx, |item, _| {
 9829            item.set_has_deleted_file(true);
 9830        });
 9831
 9832        // Emit UpdateTab event to trigger the close behavior
 9833        cx.run_until_parked();
 9834        item.update(cx, |_, cx| {
 9835            cx.emit(ItemEvent::UpdateTab);
 9836        });
 9837
 9838        // Allow any potential close operation to complete
 9839        cx.run_until_parked();
 9840
 9841        // Verify the item remains open (dirty files are not auto-closed)
 9842        pane.read_with(cx, |pane, _| {
 9843            assert_eq!(
 9844                pane.items().count(),
 9845                1,
 9846                "Dirty items should not be automatically closed even when file is deleted"
 9847            );
 9848        });
 9849
 9850        // Verify the item is marked as deleted and still dirty
 9851        item.read_with(cx, |item, _| {
 9852            assert!(
 9853                item.has_deleted_file,
 9854                "Item should be marked as having deleted file"
 9855            );
 9856            assert!(item.is_dirty, "Item should still be dirty");
 9857        });
 9858    }
 9859
 9860    /// Tests that navigation history is cleaned up when files are auto-closed
 9861    /// due to deletion from disk.
 9862    #[gpui::test]
 9863    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
 9864        init_test(cx);
 9865
 9866        // Enable the close_on_file_delete setting
 9867        cx.update_global(|store: &mut SettingsStore, cx| {
 9868            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9869                settings.close_on_file_delete = Some(true);
 9870            });
 9871        });
 9872
 9873        let fs = FakeFs::new(cx.background_executor.clone());
 9874        let project = Project::test(fs, [], cx).await;
 9875        let (workspace, cx) =
 9876            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9877        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9878
 9879        // Create test items
 9880        let item1 = cx.new(|cx| {
 9881            TestItem::new(cx)
 9882                .with_label("test1.txt")
 9883                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
 9884        });
 9885        let item1_id = item1.item_id();
 9886
 9887        let item2 = cx.new(|cx| {
 9888            TestItem::new(cx)
 9889                .with_label("test2.txt")
 9890                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
 9891        });
 9892
 9893        // Add items to workspace
 9894        workspace.update_in(cx, |workspace, window, cx| {
 9895            workspace.add_item(
 9896                pane.clone(),
 9897                Box::new(item1.clone()),
 9898                None,
 9899                false,
 9900                false,
 9901                window,
 9902                cx,
 9903            );
 9904            workspace.add_item(
 9905                pane.clone(),
 9906                Box::new(item2.clone()),
 9907                None,
 9908                false,
 9909                false,
 9910                window,
 9911                cx,
 9912            );
 9913        });
 9914
 9915        // Activate item1 to ensure it gets navigation entries
 9916        pane.update_in(cx, |pane, window, cx| {
 9917            pane.activate_item(0, true, true, window, cx);
 9918        });
 9919
 9920        // Switch to item2 and back to create navigation history
 9921        pane.update_in(cx, |pane, window, cx| {
 9922            pane.activate_item(1, true, true, window, cx);
 9923        });
 9924        cx.run_until_parked();
 9925
 9926        pane.update_in(cx, |pane, window, cx| {
 9927            pane.activate_item(0, true, true, window, cx);
 9928        });
 9929        cx.run_until_parked();
 9930
 9931        // Simulate file deletion for item1
 9932        item1.update(cx, |item, _| {
 9933            item.set_has_deleted_file(true);
 9934        });
 9935
 9936        // Emit UpdateTab event to trigger the close behavior
 9937        item1.update(cx, |_, cx| {
 9938            cx.emit(ItemEvent::UpdateTab);
 9939        });
 9940        cx.run_until_parked();
 9941
 9942        // Verify item1 was closed
 9943        pane.read_with(cx, |pane, _| {
 9944            assert_eq!(
 9945                pane.items().count(),
 9946                1,
 9947                "Should have 1 item remaining after auto-close"
 9948            );
 9949        });
 9950
 9951        // Check navigation history after close
 9952        let has_item = pane.read_with(cx, |pane, cx| {
 9953            let mut has_item = false;
 9954            pane.nav_history().for_each_entry(cx, |entry, _| {
 9955                if entry.item.id() == item1_id {
 9956                    has_item = true;
 9957                }
 9958            });
 9959            has_item
 9960        });
 9961
 9962        assert!(
 9963            !has_item,
 9964            "Navigation history should not contain closed item entries"
 9965        );
 9966    }
 9967
 9968    #[gpui::test]
 9969    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
 9970        cx: &mut TestAppContext,
 9971    ) {
 9972        init_test(cx);
 9973
 9974        let fs = FakeFs::new(cx.background_executor.clone());
 9975        let project = Project::test(fs, [], cx).await;
 9976        let (workspace, cx) =
 9977            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9978        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9979
 9980        let dirty_regular_buffer = cx.new(|cx| {
 9981            TestItem::new(cx)
 9982                .with_dirty(true)
 9983                .with_label("1.txt")
 9984                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9985        });
 9986        let dirty_regular_buffer_2 = cx.new(|cx| {
 9987            TestItem::new(cx)
 9988                .with_dirty(true)
 9989                .with_label("2.txt")
 9990                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9991        });
 9992        let clear_regular_buffer = cx.new(|cx| {
 9993            TestItem::new(cx)
 9994                .with_label("3.txt")
 9995                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9996        });
 9997
 9998        let dirty_multi_buffer = cx.new(|cx| {
 9999            TestItem::new(cx)
10000                .with_dirty(true)
10001                .with_singleton(false)
10002                .with_label("Fake Project Search")
10003                .with_project_items(&[
10004                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10005                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10006                    clear_regular_buffer.read(cx).project_items[0].clone(),
10007                ])
10008        });
10009        workspace.update_in(cx, |workspace, window, cx| {
10010            workspace.add_item(
10011                pane.clone(),
10012                Box::new(dirty_regular_buffer.clone()),
10013                None,
10014                false,
10015                false,
10016                window,
10017                cx,
10018            );
10019            workspace.add_item(
10020                pane.clone(),
10021                Box::new(dirty_regular_buffer_2.clone()),
10022                None,
10023                false,
10024                false,
10025                window,
10026                cx,
10027            );
10028            workspace.add_item(
10029                pane.clone(),
10030                Box::new(dirty_multi_buffer.clone()),
10031                None,
10032                false,
10033                false,
10034                window,
10035                cx,
10036            );
10037        });
10038
10039        pane.update_in(cx, |pane, window, cx| {
10040            pane.activate_item(2, true, true, window, cx);
10041            assert_eq!(
10042                pane.active_item().unwrap().item_id(),
10043                dirty_multi_buffer.item_id(),
10044                "Should select the multi buffer in the pane"
10045            );
10046        });
10047        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10048            pane.close_active_item(
10049                &CloseActiveItem {
10050                    save_intent: None,
10051                    close_pinned: false,
10052                },
10053                window,
10054                cx,
10055            )
10056        });
10057        cx.background_executor.run_until_parked();
10058        assert!(
10059            !cx.has_pending_prompt(),
10060            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10061        );
10062        close_multi_buffer_task
10063            .await
10064            .expect("Closing multi buffer failed");
10065        pane.update(cx, |pane, cx| {
10066            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10067            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10068            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10069            assert_eq!(
10070                pane.items()
10071                    .map(|item| item.item_id())
10072                    .sorted()
10073                    .collect::<Vec<_>>(),
10074                vec![
10075                    dirty_regular_buffer.item_id(),
10076                    dirty_regular_buffer_2.item_id(),
10077                ],
10078                "Should have no multi buffer left in the pane"
10079            );
10080            assert!(dirty_regular_buffer.read(cx).is_dirty);
10081            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10082        });
10083    }
10084
10085    #[gpui::test]
10086    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10087        init_test(cx);
10088        let fs = FakeFs::new(cx.executor());
10089        let project = Project::test(fs, [], cx).await;
10090        let (workspace, cx) =
10091            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10092
10093        // Add a new panel to the right dock, opening the dock and setting the
10094        // focus to the new panel.
10095        let panel = workspace.update_in(cx, |workspace, window, cx| {
10096            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10097            workspace.add_panel(panel.clone(), window, cx);
10098
10099            workspace
10100                .right_dock()
10101                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10102
10103            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10104
10105            panel
10106        });
10107
10108        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10109        // panel to the next valid position which, in this case, is the left
10110        // dock.
10111        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10112        workspace.update(cx, |workspace, cx| {
10113            assert!(workspace.left_dock().read(cx).is_open());
10114            assert_eq!(panel.read(cx).position, DockPosition::Left);
10115        });
10116
10117        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10118        // panel to the next valid position which, in this case, is the bottom
10119        // dock.
10120        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10121        workspace.update(cx, |workspace, cx| {
10122            assert!(workspace.bottom_dock().read(cx).is_open());
10123            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10124        });
10125
10126        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10127        // around moving the panel to its initial position, the right dock.
10128        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10129        workspace.update(cx, |workspace, cx| {
10130            assert!(workspace.right_dock().read(cx).is_open());
10131            assert_eq!(panel.read(cx).position, DockPosition::Right);
10132        });
10133
10134        // Remove focus from the panel, ensuring that, if the panel is not
10135        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10136        // the panel's position, so the panel is still in the right dock.
10137        workspace.update_in(cx, |workspace, window, cx| {
10138            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10139        });
10140
10141        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10142        workspace.update(cx, |workspace, cx| {
10143            assert!(workspace.right_dock().read(cx).is_open());
10144            assert_eq!(panel.read(cx).position, DockPosition::Right);
10145        });
10146    }
10147
10148    #[gpui::test]
10149    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10150        init_test(cx);
10151
10152        let fs = FakeFs::new(cx.executor());
10153        let project = Project::test(fs, [], cx).await;
10154        let (workspace, cx) =
10155            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10156
10157        let item_1 = cx.new(|cx| {
10158            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10159        });
10160        workspace.update_in(cx, |workspace, window, cx| {
10161            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10162            workspace.move_item_to_pane_in_direction(
10163                &MoveItemToPaneInDirection {
10164                    direction: SplitDirection::Right,
10165                    focus: true,
10166                    clone: false,
10167                },
10168                window,
10169                cx,
10170            );
10171            workspace.move_item_to_pane_at_index(
10172                &MoveItemToPane {
10173                    destination: 3,
10174                    focus: true,
10175                    clone: false,
10176                },
10177                window,
10178                cx,
10179            );
10180
10181            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10182            assert_eq!(
10183                pane_items_paths(&workspace.active_pane, cx),
10184                vec!["first.txt".to_string()],
10185                "Single item was not moved anywhere"
10186            );
10187        });
10188
10189        let item_2 = cx.new(|cx| {
10190            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10191        });
10192        workspace.update_in(cx, |workspace, window, cx| {
10193            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10194            assert_eq!(
10195                pane_items_paths(&workspace.panes[0], cx),
10196                vec!["first.txt".to_string(), "second.txt".to_string()],
10197            );
10198            workspace.move_item_to_pane_in_direction(
10199                &MoveItemToPaneInDirection {
10200                    direction: SplitDirection::Right,
10201                    focus: true,
10202                    clone: false,
10203                },
10204                window,
10205                cx,
10206            );
10207
10208            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10209            assert_eq!(
10210                pane_items_paths(&workspace.panes[0], cx),
10211                vec!["first.txt".to_string()],
10212                "After moving, one item should be left in the original pane"
10213            );
10214            assert_eq!(
10215                pane_items_paths(&workspace.panes[1], cx),
10216                vec!["second.txt".to_string()],
10217                "New item should have been moved to the new pane"
10218            );
10219        });
10220
10221        let item_3 = cx.new(|cx| {
10222            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10223        });
10224        workspace.update_in(cx, |workspace, window, cx| {
10225            let original_pane = workspace.panes[0].clone();
10226            workspace.set_active_pane(&original_pane, window, cx);
10227            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10228            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10229            assert_eq!(
10230                pane_items_paths(&workspace.active_pane, cx),
10231                vec!["first.txt".to_string(), "third.txt".to_string()],
10232                "New pane should be ready to move one item out"
10233            );
10234
10235            workspace.move_item_to_pane_at_index(
10236                &MoveItemToPane {
10237                    destination: 3,
10238                    focus: true,
10239                    clone: false,
10240                },
10241                window,
10242                cx,
10243            );
10244            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10245            assert_eq!(
10246                pane_items_paths(&workspace.active_pane, cx),
10247                vec!["first.txt".to_string()],
10248                "After moving, one item should be left in the original pane"
10249            );
10250            assert_eq!(
10251                pane_items_paths(&workspace.panes[1], cx),
10252                vec!["second.txt".to_string()],
10253                "Previously created pane should be unchanged"
10254            );
10255            assert_eq!(
10256                pane_items_paths(&workspace.panes[2], cx),
10257                vec!["third.txt".to_string()],
10258                "New item should have been moved to the new pane"
10259            );
10260        });
10261    }
10262
10263    #[gpui::test]
10264    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10265        init_test(cx);
10266
10267        let fs = FakeFs::new(cx.executor());
10268        let project = Project::test(fs, [], cx).await;
10269        let (workspace, cx) =
10270            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10271
10272        let item_1 = cx.new(|cx| {
10273            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10274        });
10275        workspace.update_in(cx, |workspace, window, cx| {
10276            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10277            workspace.move_item_to_pane_in_direction(
10278                &MoveItemToPaneInDirection {
10279                    direction: SplitDirection::Right,
10280                    focus: true,
10281                    clone: true,
10282                },
10283                window,
10284                cx,
10285            );
10286            workspace.move_item_to_pane_at_index(
10287                &MoveItemToPane {
10288                    destination: 3,
10289                    focus: true,
10290                    clone: true,
10291                },
10292                window,
10293                cx,
10294            );
10295
10296            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10297            for pane in workspace.panes() {
10298                assert_eq!(
10299                    pane_items_paths(pane, cx),
10300                    vec!["first.txt".to_string()],
10301                    "Single item exists in all panes"
10302                );
10303            }
10304        });
10305
10306        // verify that the active pane has been updated after waiting for the
10307        // pane focus event to fire and resolve
10308        workspace.read_with(cx, |workspace, _app| {
10309            assert_eq!(
10310                workspace.active_pane(),
10311                &workspace.panes[2],
10312                "The third pane should be the active one: {:?}",
10313                workspace.panes
10314            );
10315        })
10316    }
10317
10318    mod register_project_item_tests {
10319
10320        use super::*;
10321
10322        // View
10323        struct TestPngItemView {
10324            focus_handle: FocusHandle,
10325        }
10326        // Model
10327        struct TestPngItem {}
10328
10329        impl project::ProjectItem for TestPngItem {
10330            fn try_open(
10331                _project: &Entity<Project>,
10332                path: &ProjectPath,
10333                cx: &mut App,
10334            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10335                if path.path.extension().unwrap() == "png" {
10336                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10337                } else {
10338                    None
10339                }
10340            }
10341
10342            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10343                None
10344            }
10345
10346            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10347                None
10348            }
10349
10350            fn is_dirty(&self) -> bool {
10351                false
10352            }
10353        }
10354
10355        impl Item for TestPngItemView {
10356            type Event = ();
10357            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10358                "".into()
10359            }
10360        }
10361        impl EventEmitter<()> for TestPngItemView {}
10362        impl Focusable for TestPngItemView {
10363            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10364                self.focus_handle.clone()
10365            }
10366        }
10367
10368        impl Render for TestPngItemView {
10369            fn render(
10370                &mut self,
10371                _window: &mut Window,
10372                _cx: &mut Context<Self>,
10373            ) -> impl IntoElement {
10374                Empty
10375            }
10376        }
10377
10378        impl ProjectItem for TestPngItemView {
10379            type Item = TestPngItem;
10380
10381            fn for_project_item(
10382                _project: Entity<Project>,
10383                _pane: Option<&Pane>,
10384                _item: Entity<Self::Item>,
10385                _: &mut Window,
10386                cx: &mut Context<Self>,
10387            ) -> Self
10388            where
10389                Self: Sized,
10390            {
10391                Self {
10392                    focus_handle: cx.focus_handle(),
10393                }
10394            }
10395        }
10396
10397        // View
10398        struct TestIpynbItemView {
10399            focus_handle: FocusHandle,
10400        }
10401        // Model
10402        struct TestIpynbItem {}
10403
10404        impl project::ProjectItem for TestIpynbItem {
10405            fn try_open(
10406                _project: &Entity<Project>,
10407                path: &ProjectPath,
10408                cx: &mut App,
10409            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10410                if path.path.extension().unwrap() == "ipynb" {
10411                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10412                } else {
10413                    None
10414                }
10415            }
10416
10417            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10418                None
10419            }
10420
10421            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10422                None
10423            }
10424
10425            fn is_dirty(&self) -> bool {
10426                false
10427            }
10428        }
10429
10430        impl Item for TestIpynbItemView {
10431            type Event = ();
10432            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10433                "".into()
10434            }
10435        }
10436        impl EventEmitter<()> for TestIpynbItemView {}
10437        impl Focusable for TestIpynbItemView {
10438            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10439                self.focus_handle.clone()
10440            }
10441        }
10442
10443        impl Render for TestIpynbItemView {
10444            fn render(
10445                &mut self,
10446                _window: &mut Window,
10447                _cx: &mut Context<Self>,
10448            ) -> impl IntoElement {
10449                Empty
10450            }
10451        }
10452
10453        impl ProjectItem for TestIpynbItemView {
10454            type Item = TestIpynbItem;
10455
10456            fn for_project_item(
10457                _project: Entity<Project>,
10458                _pane: Option<&Pane>,
10459                _item: Entity<Self::Item>,
10460                _: &mut Window,
10461                cx: &mut Context<Self>,
10462            ) -> Self
10463            where
10464                Self: Sized,
10465            {
10466                Self {
10467                    focus_handle: cx.focus_handle(),
10468                }
10469            }
10470        }
10471
10472        struct TestAlternatePngItemView {
10473            focus_handle: FocusHandle,
10474        }
10475
10476        impl Item for TestAlternatePngItemView {
10477            type Event = ();
10478            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10479                "".into()
10480            }
10481        }
10482
10483        impl EventEmitter<()> for TestAlternatePngItemView {}
10484        impl Focusable for TestAlternatePngItemView {
10485            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10486                self.focus_handle.clone()
10487            }
10488        }
10489
10490        impl Render for TestAlternatePngItemView {
10491            fn render(
10492                &mut self,
10493                _window: &mut Window,
10494                _cx: &mut Context<Self>,
10495            ) -> impl IntoElement {
10496                Empty
10497            }
10498        }
10499
10500        impl ProjectItem for TestAlternatePngItemView {
10501            type Item = TestPngItem;
10502
10503            fn for_project_item(
10504                _project: Entity<Project>,
10505                _pane: Option<&Pane>,
10506                _item: Entity<Self::Item>,
10507                _: &mut Window,
10508                cx: &mut Context<Self>,
10509            ) -> Self
10510            where
10511                Self: Sized,
10512            {
10513                Self {
10514                    focus_handle: cx.focus_handle(),
10515                }
10516            }
10517        }
10518
10519        #[gpui::test]
10520        async fn test_register_project_item(cx: &mut TestAppContext) {
10521            init_test(cx);
10522
10523            cx.update(|cx| {
10524                register_project_item::<TestPngItemView>(cx);
10525                register_project_item::<TestIpynbItemView>(cx);
10526            });
10527
10528            let fs = FakeFs::new(cx.executor());
10529            fs.insert_tree(
10530                "/root1",
10531                json!({
10532                    "one.png": "BINARYDATAHERE",
10533                    "two.ipynb": "{ totally a notebook }",
10534                    "three.txt": "editing text, sure why not?"
10535                }),
10536            )
10537            .await;
10538
10539            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10540            let (workspace, cx) =
10541                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10542
10543            let worktree_id = project.update(cx, |project, cx| {
10544                project.worktrees(cx).next().unwrap().read(cx).id()
10545            });
10546
10547            let handle = workspace
10548                .update_in(cx, |workspace, window, cx| {
10549                    let project_path = (worktree_id, "one.png");
10550                    workspace.open_path(project_path, None, true, window, cx)
10551                })
10552                .await
10553                .unwrap();
10554
10555            // Now we can check if the handle we got back errored or not
10556            assert_eq!(
10557                handle.to_any().entity_type(),
10558                TypeId::of::<TestPngItemView>()
10559            );
10560
10561            let handle = workspace
10562                .update_in(cx, |workspace, window, cx| {
10563                    let project_path = (worktree_id, "two.ipynb");
10564                    workspace.open_path(project_path, None, true, window, cx)
10565                })
10566                .await
10567                .unwrap();
10568
10569            assert_eq!(
10570                handle.to_any().entity_type(),
10571                TypeId::of::<TestIpynbItemView>()
10572            );
10573
10574            let handle = workspace
10575                .update_in(cx, |workspace, window, cx| {
10576                    let project_path = (worktree_id, "three.txt");
10577                    workspace.open_path(project_path, None, true, window, cx)
10578                })
10579                .await;
10580            assert!(handle.is_err());
10581        }
10582
10583        #[gpui::test]
10584        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10585            init_test(cx);
10586
10587            cx.update(|cx| {
10588                register_project_item::<TestPngItemView>(cx);
10589                register_project_item::<TestAlternatePngItemView>(cx);
10590            });
10591
10592            let fs = FakeFs::new(cx.executor());
10593            fs.insert_tree(
10594                "/root1",
10595                json!({
10596                    "one.png": "BINARYDATAHERE",
10597                    "two.ipynb": "{ totally a notebook }",
10598                    "three.txt": "editing text, sure why not?"
10599                }),
10600            )
10601            .await;
10602            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10603            let (workspace, cx) =
10604                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10605            let worktree_id = project.update(cx, |project, cx| {
10606                project.worktrees(cx).next().unwrap().read(cx).id()
10607            });
10608
10609            let handle = workspace
10610                .update_in(cx, |workspace, window, cx| {
10611                    let project_path = (worktree_id, "one.png");
10612                    workspace.open_path(project_path, None, true, window, cx)
10613                })
10614                .await
10615                .unwrap();
10616
10617            // This _must_ be the second item registered
10618            assert_eq!(
10619                handle.to_any().entity_type(),
10620                TypeId::of::<TestAlternatePngItemView>()
10621            );
10622
10623            let handle = workspace
10624                .update_in(cx, |workspace, window, cx| {
10625                    let project_path = (worktree_id, "three.txt");
10626                    workspace.open_path(project_path, None, true, window, cx)
10627                })
10628                .await;
10629            assert!(handle.is_err());
10630        }
10631    }
10632
10633    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10634        pane.read(cx)
10635            .items()
10636            .flat_map(|item| {
10637                item.project_paths(cx)
10638                    .into_iter()
10639                    .map(|path| path.path.to_string_lossy().to_string())
10640            })
10641            .collect()
10642    }
10643
10644    pub fn init_test(cx: &mut TestAppContext) {
10645        cx.update(|cx| {
10646            let settings_store = SettingsStore::test(cx);
10647            cx.set_global(settings_store);
10648            theme::init(theme::LoadThemes::JustBase, cx);
10649            language::init(cx);
10650            crate::init_settings(cx);
10651            Project::init_settings(cx);
10652        });
10653    }
10654
10655    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10656        let item = TestProjectItem::new(id, path, cx);
10657        item.update(cx, |item, _| {
10658            item.is_dirty = true;
10659        });
10660        item
10661    }
10662}