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