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