workspace.rs

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