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