workspace.rs

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