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