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(¢er_pane, window, Self::handle_pane_event)
 1345            .detach();
 1346
 1347        window.focus(¢er_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(¢er_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 ×tamp > 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(¬ification_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(¬ification_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 ¬ification_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        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 7093        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7094        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7095        OpenChannelNotes,
 7096        /// Mutes your microphone.
 7097        Mute,
 7098        /// Deafens yourself (mute both microphone and speakers).
 7099        Deafen,
 7100        /// Leaves the current call.
 7101        LeaveCall,
 7102        /// Shares the current project with collaborators.
 7103        ShareProject,
 7104        /// Shares your screen with collaborators.
 7105        ScreenShare
 7106    ]
 7107);
 7108actions!(
 7109    zed,
 7110    [
 7111        /// Opens the Zed log file.
 7112        OpenLog,
 7113        /// Reveals the Zed log file in the system file manager.
 7114        RevealLogInFileManager
 7115    ]
 7116);
 7117
 7118async fn join_channel_internal(
 7119    channel_id: ChannelId,
 7120    app_state: &Arc<AppState>,
 7121    requesting_window: Option<WindowHandle<Workspace>>,
 7122    active_call: &Entity<ActiveCall>,
 7123    cx: &mut AsyncApp,
 7124) -> Result<bool> {
 7125    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7126        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7127            return (false, None);
 7128        };
 7129
 7130        let already_in_channel = room.channel_id() == Some(channel_id);
 7131        let should_prompt = room.is_sharing_project()
 7132            && !room.remote_participants().is_empty()
 7133            && !already_in_channel;
 7134        let open_room = if already_in_channel {
 7135            active_call.room().cloned()
 7136        } else {
 7137            None
 7138        };
 7139        (should_prompt, open_room)
 7140    })?;
 7141
 7142    if let Some(room) = open_room {
 7143        let task = room.update(cx, |room, cx| {
 7144            if let Some((project, host)) = room.most_active_project(cx) {
 7145                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7146            }
 7147
 7148            None
 7149        })?;
 7150        if let Some(task) = task {
 7151            task.await?;
 7152        }
 7153        return anyhow::Ok(true);
 7154    }
 7155
 7156    if should_prompt {
 7157        if let Some(workspace) = requesting_window {
 7158            let answer = workspace
 7159                .update(cx, |_, window, cx| {
 7160                    window.prompt(
 7161                        PromptLevel::Warning,
 7162                        "Do you want to switch channels?",
 7163                        Some("Leaving this call will unshare your current project."),
 7164                        &["Yes, Join Channel", "Cancel"],
 7165                        cx,
 7166                    )
 7167                })?
 7168                .await;
 7169
 7170            if answer == Ok(1) {
 7171                return Ok(false);
 7172            }
 7173        } else {
 7174            return Ok(false); // unreachable!() hopefully
 7175        }
 7176    }
 7177
 7178    let client = cx.update(|cx| active_call.read(cx).client())?;
 7179
 7180    let mut client_status = client.status();
 7181
 7182    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7183    'outer: loop {
 7184        let Some(status) = client_status.recv().await else {
 7185            anyhow::bail!("error connecting");
 7186        };
 7187
 7188        match status {
 7189            Status::Connecting
 7190            | Status::Authenticating
 7191            | Status::Authenticated
 7192            | Status::Reconnecting
 7193            | Status::Reauthenticating
 7194            | Status::Reauthenticated => continue,
 7195            Status::Connected { .. } => break 'outer,
 7196            Status::SignedOut | Status::AuthenticationError => {
 7197                return Err(ErrorCode::SignedOut.into());
 7198            }
 7199            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7200            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7201                return Err(ErrorCode::Disconnected.into());
 7202            }
 7203        }
 7204    }
 7205
 7206    let room = active_call
 7207        .update(cx, |active_call, cx| {
 7208            active_call.join_channel(channel_id, cx)
 7209        })?
 7210        .await?;
 7211
 7212    let Some(room) = room else {
 7213        return anyhow::Ok(true);
 7214    };
 7215
 7216    room.update(cx, |room, _| room.room_update_completed())?
 7217        .await;
 7218
 7219    let task = room.update(cx, |room, cx| {
 7220        if let Some((project, host)) = room.most_active_project(cx) {
 7221            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7222        }
 7223
 7224        // If you are the first to join a channel, see if you should share your project.
 7225        if room.remote_participants().is_empty()
 7226            && !room.local_participant_is_guest()
 7227            && let Some(workspace) = requesting_window
 7228        {
 7229            let project = workspace.update(cx, |workspace, _, cx| {
 7230                let project = workspace.project.read(cx);
 7231
 7232                if !CallSettings::get_global(cx).share_on_join {
 7233                    return None;
 7234                }
 7235
 7236                if (project.is_local() || project.is_via_remote_server())
 7237                    && project.visible_worktrees(cx).any(|tree| {
 7238                        tree.read(cx)
 7239                            .root_entry()
 7240                            .is_some_and(|entry| entry.is_dir())
 7241                    })
 7242                {
 7243                    Some(workspace.project.clone())
 7244                } else {
 7245                    None
 7246                }
 7247            });
 7248            if let Ok(Some(project)) = project {
 7249                return Some(cx.spawn(async move |room, cx| {
 7250                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7251                        .await?;
 7252                    Ok(())
 7253                }));
 7254            }
 7255        }
 7256
 7257        None
 7258    })?;
 7259    if let Some(task) = task {
 7260        task.await?;
 7261        return anyhow::Ok(true);
 7262    }
 7263    anyhow::Ok(false)
 7264}
 7265
 7266pub fn join_channel(
 7267    channel_id: ChannelId,
 7268    app_state: Arc<AppState>,
 7269    requesting_window: Option<WindowHandle<Workspace>>,
 7270    cx: &mut App,
 7271) -> Task<Result<()>> {
 7272    let active_call = ActiveCall::global(cx);
 7273    cx.spawn(async move |cx| {
 7274        let result = join_channel_internal(
 7275            channel_id,
 7276            &app_state,
 7277            requesting_window,
 7278            &active_call,
 7279             cx,
 7280        )
 7281            .await;
 7282
 7283        // join channel succeeded, and opened a window
 7284        if matches!(result, Ok(true)) {
 7285            return anyhow::Ok(());
 7286        }
 7287
 7288        // find an existing workspace to focus and show call controls
 7289        let mut active_window =
 7290            requesting_window.or_else(|| activate_any_workspace_window( cx));
 7291        if active_window.is_none() {
 7292            // no open workspaces, make one to show the error in (blergh)
 7293            let (window_handle, _) = cx
 7294                .update(|cx| {
 7295                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 7296                })?
 7297                .await?;
 7298
 7299            if result.is_ok() {
 7300                cx.update(|cx| {
 7301                    cx.dispatch_action(&OpenChannelNotes);
 7302                }).log_err();
 7303            }
 7304
 7305            active_window = Some(window_handle);
 7306        }
 7307
 7308        if let Err(err) = result {
 7309            log::error!("failed to join channel: {}", err);
 7310            if let Some(active_window) = active_window {
 7311                active_window
 7312                    .update(cx, |_, window, cx| {
 7313                        let detail: SharedString = match err.error_code() {
 7314                            ErrorCode::SignedOut => {
 7315                                "Please sign in to continue.".into()
 7316                            }
 7317                            ErrorCode::UpgradeRequired => {
 7318                                "Your are running an unsupported version of Zed. Please update to continue.".into()
 7319                            }
 7320                            ErrorCode::NoSuchChannel => {
 7321                                "No matching channel was found. Please check the link and try again.".into()
 7322                            }
 7323                            ErrorCode::Forbidden => {
 7324                                "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
 7325                            }
 7326                            ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
 7327                            _ => format!("{}\n\nPlease try again.", err).into(),
 7328                        };
 7329                        window.prompt(
 7330                            PromptLevel::Critical,
 7331                            "Failed to join channel",
 7332                            Some(&detail),
 7333                            &["Ok"],
 7334                        cx)
 7335                    })?
 7336                    .await
 7337                    .ok();
 7338            }
 7339        }
 7340
 7341        // return ok, we showed the error to the user.
 7342        anyhow::Ok(())
 7343    })
 7344}
 7345
 7346pub async fn get_any_active_workspace(
 7347    app_state: Arc<AppState>,
 7348    mut cx: AsyncApp,
 7349) -> anyhow::Result<WindowHandle<Workspace>> {
 7350    // find an existing workspace to focus and show call controls
 7351    let active_window = activate_any_workspace_window(&mut cx);
 7352    if active_window.is_none() {
 7353        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 7354            .await?;
 7355    }
 7356    activate_any_workspace_window(&mut cx).context("could not open zed")
 7357}
 7358
 7359fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7360    cx.update(|cx| {
 7361        if let Some(workspace_window) = cx
 7362            .active_window()
 7363            .and_then(|window| window.downcast::<Workspace>())
 7364        {
 7365            return Some(workspace_window);
 7366        }
 7367
 7368        for window in cx.windows() {
 7369            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7370                workspace_window
 7371                    .update(cx, |_, window, _| window.activate_window())
 7372                    .ok();
 7373                return Some(workspace_window);
 7374            }
 7375        }
 7376        None
 7377    })
 7378    .ok()
 7379    .flatten()
 7380}
 7381
 7382pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7383    cx.windows()
 7384        .into_iter()
 7385        .filter_map(|window| window.downcast::<Workspace>())
 7386        .filter(|workspace| {
 7387            workspace
 7388                .read(cx)
 7389                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7390        })
 7391        .collect()
 7392}
 7393
 7394#[derive(Default)]
 7395pub struct OpenOptions {
 7396    pub visible: Option<OpenVisible>,
 7397    pub focus: Option<bool>,
 7398    pub open_new_workspace: Option<bool>,
 7399    pub prefer_focused_window: bool,
 7400    pub replace_window: Option<WindowHandle<Workspace>>,
 7401    pub env: Option<HashMap<String, String>>,
 7402}
 7403
 7404#[allow(clippy::type_complexity)]
 7405pub fn open_paths(
 7406    abs_paths: &[PathBuf],
 7407    app_state: Arc<AppState>,
 7408    open_options: OpenOptions,
 7409    cx: &mut App,
 7410) -> Task<
 7411    anyhow::Result<(
 7412        WindowHandle<Workspace>,
 7413        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7414    )>,
 7415> {
 7416    let abs_paths = abs_paths.to_vec();
 7417    let mut existing = None;
 7418    let mut best_match = None;
 7419    let mut open_visible = OpenVisible::All;
 7420    #[cfg(target_os = "windows")]
 7421    let wsl_path = abs_paths
 7422        .iter()
 7423        .find_map(|p| util::paths::WslPath::from_path(p));
 7424
 7425    cx.spawn(async move |cx| {
 7426        if open_options.open_new_workspace != Some(true) {
 7427            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7428            let all_metadatas = futures::future::join_all(all_paths)
 7429                .await
 7430                .into_iter()
 7431                .filter_map(|result| result.ok().flatten())
 7432                .collect::<Vec<_>>();
 7433
 7434            cx.update(|cx| {
 7435                for window in local_workspace_windows(cx) {
 7436                    if let Ok(workspace) = window.read(cx) {
 7437                        let m = workspace.project.read(cx).visibility_for_paths(
 7438                            &abs_paths,
 7439                            &all_metadatas,
 7440                            open_options.open_new_workspace == None,
 7441                            cx,
 7442                        );
 7443                        if m > best_match {
 7444                            existing = Some(window);
 7445                            best_match = m;
 7446                        } else if best_match.is_none()
 7447                            && open_options.open_new_workspace == Some(false)
 7448                        {
 7449                            existing = Some(window)
 7450                        }
 7451                    }
 7452                }
 7453            })?;
 7454
 7455            if open_options.open_new_workspace.is_none()
 7456                && (existing.is_none() || open_options.prefer_focused_window)
 7457                && all_metadatas.iter().all(|file| !file.is_dir)
 7458            {
 7459                cx.update(|cx| {
 7460                    if let Some(window) = cx
 7461                        .active_window()
 7462                        .and_then(|window| window.downcast::<Workspace>())
 7463                        && let Ok(workspace) = window.read(cx)
 7464                    {
 7465                        let project = workspace.project().read(cx);
 7466                        if project.is_local() && !project.is_via_collab() {
 7467                            existing = Some(window);
 7468                            open_visible = OpenVisible::None;
 7469                            return;
 7470                        }
 7471                    }
 7472                    for window in local_workspace_windows(cx) {
 7473                        if let Ok(workspace) = window.read(cx) {
 7474                            let project = workspace.project().read(cx);
 7475                            if project.is_via_collab() {
 7476                                continue;
 7477                            }
 7478                            existing = Some(window);
 7479                            open_visible = OpenVisible::None;
 7480                            break;
 7481                        }
 7482                    }
 7483                })?;
 7484            }
 7485        }
 7486
 7487        let result = if let Some(existing) = existing {
 7488            let open_task = existing
 7489                .update(cx, |workspace, window, cx| {
 7490                    window.activate_window();
 7491                    workspace.open_paths(
 7492                        abs_paths,
 7493                        OpenOptions {
 7494                            visible: Some(open_visible),
 7495                            ..Default::default()
 7496                        },
 7497                        None,
 7498                        window,
 7499                        cx,
 7500                    )
 7501                })?
 7502                .await;
 7503
 7504            _ = existing.update(cx, |workspace, _, cx| {
 7505                for item in open_task.iter().flatten() {
 7506                    if let Err(e) = item {
 7507                        workspace.show_error(&e, cx);
 7508                    }
 7509                }
 7510            });
 7511
 7512            Ok((existing, open_task))
 7513        } else {
 7514            cx.update(move |cx| {
 7515                Workspace::new_local(
 7516                    abs_paths,
 7517                    app_state.clone(),
 7518                    open_options.replace_window,
 7519                    open_options.env,
 7520                    cx,
 7521                )
 7522            })?
 7523            .await
 7524        };
 7525
 7526        #[cfg(target_os = "windows")]
 7527        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 7528            && let Ok((workspace, _)) = &result
 7529        {
 7530            workspace
 7531                .update(cx, move |workspace, _window, cx| {
 7532                    struct OpenInWsl;
 7533                    workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 7534                        let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 7535                        let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 7536                        cx.new(move |cx| {
 7537                            MessageNotification::new(msg, cx)
 7538                                .primary_message("Open in WSL")
 7539                                .primary_icon(IconName::FolderOpen)
 7540                                .primary_on_click(move |window, cx| {
 7541                                    window.dispatch_action(Box::new(remote::OpenWslPath {
 7542                                            distro: remote::WslConnectionOptions {
 7543                                                    distro_name: distro.clone(),
 7544                                                user: None,
 7545                                            },
 7546                                            paths: vec![path.clone().into()],
 7547                                        }), cx)
 7548                                })
 7549                        })
 7550                    });
 7551                })
 7552                .unwrap();
 7553        };
 7554        result
 7555    })
 7556}
 7557
 7558pub fn open_new(
 7559    open_options: OpenOptions,
 7560    app_state: Arc<AppState>,
 7561    cx: &mut App,
 7562    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7563) -> Task<anyhow::Result<()>> {
 7564    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7565    cx.spawn(async move |cx| {
 7566        let (workspace, opened_paths) = task.await?;
 7567        workspace.update(cx, |workspace, window, cx| {
 7568            if opened_paths.is_empty() {
 7569                init(workspace, window, cx)
 7570            }
 7571        })?;
 7572        Ok(())
 7573    })
 7574}
 7575
 7576pub fn create_and_open_local_file(
 7577    path: &'static Path,
 7578    window: &mut Window,
 7579    cx: &mut Context<Workspace>,
 7580    default_content: impl 'static + Send + FnOnce() -> Rope,
 7581) -> Task<Result<Box<dyn ItemHandle>>> {
 7582    cx.spawn_in(window, async move |workspace, cx| {
 7583        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7584        if !fs.is_file(path).await {
 7585            fs.create_file(path, Default::default()).await?;
 7586            fs.save(path, &default_content(), Default::default())
 7587                .await?;
 7588        }
 7589
 7590        let mut items = workspace
 7591            .update_in(cx, |workspace, window, cx| {
 7592                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7593                    workspace.open_paths(
 7594                        vec![path.to_path_buf()],
 7595                        OpenOptions {
 7596                            visible: Some(OpenVisible::None),
 7597                            ..Default::default()
 7598                        },
 7599                        None,
 7600                        window,
 7601                        cx,
 7602                    )
 7603                })
 7604            })?
 7605            .await?
 7606            .await;
 7607
 7608        let item = items.pop().flatten();
 7609        item.with_context(|| format!("path {path:?} is not a file"))?
 7610    })
 7611}
 7612
 7613pub fn open_remote_project_with_new_connection(
 7614    window: WindowHandle<Workspace>,
 7615    remote_connection: Arc<dyn RemoteConnection>,
 7616    cancel_rx: oneshot::Receiver<()>,
 7617    delegate: Arc<dyn RemoteClientDelegate>,
 7618    app_state: Arc<AppState>,
 7619    paths: Vec<PathBuf>,
 7620    cx: &mut App,
 7621) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7622    cx.spawn(async move |cx| {
 7623        let (workspace_id, serialized_workspace) =
 7624            serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 7625                .await?;
 7626
 7627        let session = match cx
 7628            .update(|cx| {
 7629                remote::RemoteClient::new(
 7630                    ConnectionIdentifier::Workspace(workspace_id.0),
 7631                    remote_connection,
 7632                    cancel_rx,
 7633                    delegate,
 7634                    cx,
 7635                )
 7636            })?
 7637            .await?
 7638        {
 7639            Some(result) => result,
 7640            None => return Ok(Vec::new()),
 7641        };
 7642
 7643        let project = cx.update(|cx| {
 7644            project::Project::remote(
 7645                session,
 7646                app_state.client.clone(),
 7647                app_state.node_runtime.clone(),
 7648                app_state.user_store.clone(),
 7649                app_state.languages.clone(),
 7650                app_state.fs.clone(),
 7651                cx,
 7652            )
 7653        })?;
 7654
 7655        open_remote_project_inner(
 7656            project,
 7657            paths,
 7658            workspace_id,
 7659            serialized_workspace,
 7660            app_state,
 7661            window,
 7662            cx,
 7663        )
 7664        .await
 7665    })
 7666}
 7667
 7668pub fn open_remote_project_with_existing_connection(
 7669    connection_options: RemoteConnectionOptions,
 7670    project: Entity<Project>,
 7671    paths: Vec<PathBuf>,
 7672    app_state: Arc<AppState>,
 7673    window: WindowHandle<Workspace>,
 7674    cx: &mut AsyncApp,
 7675) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7676    cx.spawn(async move |cx| {
 7677        let (workspace_id, serialized_workspace) =
 7678            serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7679
 7680        open_remote_project_inner(
 7681            project,
 7682            paths,
 7683            workspace_id,
 7684            serialized_workspace,
 7685            app_state,
 7686            window,
 7687            cx,
 7688        )
 7689        .await
 7690    })
 7691}
 7692
 7693async fn open_remote_project_inner(
 7694    project: Entity<Project>,
 7695    paths: Vec<PathBuf>,
 7696    workspace_id: WorkspaceId,
 7697    serialized_workspace: Option<SerializedWorkspace>,
 7698    app_state: Arc<AppState>,
 7699    window: WindowHandle<Workspace>,
 7700    cx: &mut AsyncApp,
 7701) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 7702    let toolchains = DB.toolchains(workspace_id).await?;
 7703    for (toolchain, worktree_id, path) in toolchains {
 7704        project
 7705            .update(cx, |this, cx| {
 7706                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7707            })?
 7708            .await;
 7709    }
 7710    let mut project_paths_to_open = vec![];
 7711    let mut project_path_errors = vec![];
 7712
 7713    for path in paths {
 7714        let result = cx
 7715            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7716            .await;
 7717        match result {
 7718            Ok((_, project_path)) => {
 7719                project_paths_to_open.push((path.clone(), Some(project_path)));
 7720            }
 7721            Err(error) => {
 7722                project_path_errors.push(error);
 7723            }
 7724        };
 7725    }
 7726
 7727    if project_paths_to_open.is_empty() {
 7728        return Err(project_path_errors.pop().context("no paths given")?);
 7729    }
 7730
 7731    if let Some(detach_session_task) = window
 7732        .update(cx, |_workspace, window, cx| {
 7733            cx.spawn_in(window, async move |this, cx| {
 7734                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 7735            })
 7736        })
 7737        .ok()
 7738    {
 7739        detach_session_task.await.ok();
 7740    }
 7741
 7742    cx.update_window(window.into(), |_, window, cx| {
 7743        window.replace_root(cx, |window, cx| {
 7744            telemetry::event!("SSH Project Opened");
 7745
 7746            let mut workspace =
 7747                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7748            workspace.update_history(cx);
 7749
 7750            if let Some(ref serialized) = serialized_workspace {
 7751                workspace.centered_layout = serialized.centered_layout;
 7752            }
 7753
 7754            workspace
 7755        });
 7756    })?;
 7757
 7758    let items = window
 7759        .update(cx, |_, window, cx| {
 7760            window.activate_window();
 7761            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7762        })?
 7763        .await?;
 7764
 7765    window.update(cx, |workspace, _, cx| {
 7766        for error in project_path_errors {
 7767            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7768                if let Some(path) = error.error_tag("path") {
 7769                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7770                }
 7771            } else {
 7772                workspace.show_error(&error, cx)
 7773            }
 7774        }
 7775    })?;
 7776
 7777    Ok(items.into_iter().map(|item| item?.ok()).collect())
 7778}
 7779
 7780fn serialize_remote_project(
 7781    connection_options: RemoteConnectionOptions,
 7782    paths: Vec<PathBuf>,
 7783    cx: &AsyncApp,
 7784) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7785    cx.background_spawn(async move {
 7786        let remote_connection_id = persistence::DB
 7787            .get_or_create_remote_connection(connection_options)
 7788            .await?;
 7789
 7790        let serialized_workspace =
 7791            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 7792
 7793        let workspace_id = if let Some(workspace_id) =
 7794            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7795        {
 7796            workspace_id
 7797        } else {
 7798            persistence::DB.next_id().await?
 7799        };
 7800
 7801        Ok((workspace_id, serialized_workspace))
 7802    })
 7803}
 7804
 7805pub fn join_in_room_project(
 7806    project_id: u64,
 7807    follow_user_id: u64,
 7808    app_state: Arc<AppState>,
 7809    cx: &mut App,
 7810) -> Task<Result<()>> {
 7811    let windows = cx.windows();
 7812    cx.spawn(async move |cx| {
 7813        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7814            window_handle
 7815                .downcast::<Workspace>()
 7816                .and_then(|window_handle| {
 7817                    window_handle
 7818                        .update(cx, |workspace, _window, cx| {
 7819                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7820                                Some(window_handle)
 7821                            } else {
 7822                                None
 7823                            }
 7824                        })
 7825                        .unwrap_or(None)
 7826                })
 7827        });
 7828
 7829        let workspace = if let Some(existing_workspace) = existing_workspace {
 7830            existing_workspace
 7831        } else {
 7832            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7833            let room = active_call
 7834                .read_with(cx, |call, _| call.room().cloned())?
 7835                .context("not in a call")?;
 7836            let project = room
 7837                .update(cx, |room, cx| {
 7838                    room.join_project(
 7839                        project_id,
 7840                        app_state.languages.clone(),
 7841                        app_state.fs.clone(),
 7842                        cx,
 7843                    )
 7844                })?
 7845                .await?;
 7846
 7847            let window_bounds_override = window_bounds_env_override();
 7848            cx.update(|cx| {
 7849                let mut options = (app_state.build_window_options)(None, cx);
 7850                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7851                cx.open_window(options, |window, cx| {
 7852                    cx.new(|cx| {
 7853                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7854                    })
 7855                })
 7856            })??
 7857        };
 7858
 7859        workspace.update(cx, |workspace, window, cx| {
 7860            cx.activate(true);
 7861            window.activate_window();
 7862
 7863            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7864                let follow_peer_id = room
 7865                    .read(cx)
 7866                    .remote_participants()
 7867                    .iter()
 7868                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7869                    .map(|(_, p)| p.peer_id)
 7870                    .or_else(|| {
 7871                        // If we couldn't follow the given user, follow the host instead.
 7872                        let collaborator = workspace
 7873                            .project()
 7874                            .read(cx)
 7875                            .collaborators()
 7876                            .values()
 7877                            .find(|collaborator| collaborator.is_host)?;
 7878                        Some(collaborator.peer_id)
 7879                    });
 7880
 7881                if let Some(follow_peer_id) = follow_peer_id {
 7882                    workspace.follow(follow_peer_id, window, cx);
 7883                }
 7884            }
 7885        })?;
 7886
 7887        anyhow::Ok(())
 7888    })
 7889}
 7890
 7891pub fn reload(cx: &mut App) {
 7892    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7893    let mut workspace_windows = cx
 7894        .windows()
 7895        .into_iter()
 7896        .filter_map(|window| window.downcast::<Workspace>())
 7897        .collect::<Vec<_>>();
 7898
 7899    // If multiple windows have unsaved changes, and need a save prompt,
 7900    // prompt in the active window before switching to a different window.
 7901    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7902
 7903    let mut prompt = None;
 7904    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7905        prompt = window
 7906            .update(cx, |_, window, cx| {
 7907                window.prompt(
 7908                    PromptLevel::Info,
 7909                    "Are you sure you want to restart?",
 7910                    None,
 7911                    &["Restart", "Cancel"],
 7912                    cx,
 7913                )
 7914            })
 7915            .ok();
 7916    }
 7917
 7918    cx.spawn(async move |cx| {
 7919        if let Some(prompt) = prompt {
 7920            let answer = prompt.await?;
 7921            if answer != 0 {
 7922                return Ok(());
 7923            }
 7924        }
 7925
 7926        // If the user cancels any save prompt, then keep the app open.
 7927        for window in workspace_windows {
 7928            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7929                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7930            }) && !should_close.await?
 7931            {
 7932                return Ok(());
 7933            }
 7934        }
 7935        cx.update(|cx| cx.restart())
 7936    })
 7937    .detach_and_log_err(cx);
 7938}
 7939
 7940fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7941    let mut parts = value.split(',');
 7942    let x: usize = parts.next()?.parse().ok()?;
 7943    let y: usize = parts.next()?.parse().ok()?;
 7944    Some(point(px(x as f32), px(y as f32)))
 7945}
 7946
 7947fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7948    let mut parts = value.split(',');
 7949    let width: usize = parts.next()?.parse().ok()?;
 7950    let height: usize = parts.next()?.parse().ok()?;
 7951    Some(size(px(width as f32), px(height as f32)))
 7952}
 7953
 7954/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7955pub fn client_side_decorations(
 7956    element: impl IntoElement,
 7957    window: &mut Window,
 7958    cx: &mut App,
 7959) -> Stateful<Div> {
 7960    const BORDER_SIZE: Pixels = px(1.0);
 7961    let decorations = window.window_decorations();
 7962
 7963    match decorations {
 7964        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7965        Decorations::Server => window.set_client_inset(px(0.0)),
 7966    }
 7967
 7968    struct GlobalResizeEdge(ResizeEdge);
 7969    impl Global for GlobalResizeEdge {}
 7970
 7971    div()
 7972        .id("window-backdrop")
 7973        .bg(transparent_black())
 7974        .map(|div| match decorations {
 7975            Decorations::Server => div,
 7976            Decorations::Client { tiling, .. } => div
 7977                .when(!(tiling.top || tiling.right), |div| {
 7978                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7979                })
 7980                .when(!(tiling.top || tiling.left), |div| {
 7981                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7982                })
 7983                .when(!(tiling.bottom || tiling.right), |div| {
 7984                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7985                })
 7986                .when(!(tiling.bottom || tiling.left), |div| {
 7987                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7988                })
 7989                .when(!tiling.top, |div| {
 7990                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7991                })
 7992                .when(!tiling.bottom, |div| {
 7993                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7994                })
 7995                .when(!tiling.left, |div| {
 7996                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7997                })
 7998                .when(!tiling.right, |div| {
 7999                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8000                })
 8001                .on_mouse_move(move |e, window, cx| {
 8002                    let size = window.window_bounds().get_bounds().size;
 8003                    let pos = e.position;
 8004
 8005                    let new_edge =
 8006                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8007
 8008                    let edge = cx.try_global::<GlobalResizeEdge>();
 8009                    if new_edge != edge.map(|edge| edge.0) {
 8010                        window
 8011                            .window_handle()
 8012                            .update(cx, |workspace, _, cx| {
 8013                                cx.notify(workspace.entity_id());
 8014                            })
 8015                            .ok();
 8016                    }
 8017                })
 8018                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8019                    let size = window.window_bounds().get_bounds().size;
 8020                    let pos = e.position;
 8021
 8022                    let edge = match resize_edge(
 8023                        pos,
 8024                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8025                        size,
 8026                        tiling,
 8027                    ) {
 8028                        Some(value) => value,
 8029                        None => return,
 8030                    };
 8031
 8032                    window.start_window_resize(edge);
 8033                }),
 8034        })
 8035        .size_full()
 8036        .child(
 8037            div()
 8038                .cursor(CursorStyle::Arrow)
 8039                .map(|div| match decorations {
 8040                    Decorations::Server => div,
 8041                    Decorations::Client { tiling } => div
 8042                        .border_color(cx.theme().colors().border)
 8043                        .when(!(tiling.top || tiling.right), |div| {
 8044                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8045                        })
 8046                        .when(!(tiling.top || tiling.left), |div| {
 8047                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8048                        })
 8049                        .when(!(tiling.bottom || tiling.right), |div| {
 8050                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8051                        })
 8052                        .when(!(tiling.bottom || tiling.left), |div| {
 8053                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8054                        })
 8055                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8056                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8057                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8058                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8059                        .when(!tiling.is_tiled(), |div| {
 8060                            div.shadow(vec![gpui::BoxShadow {
 8061                                color: Hsla {
 8062                                    h: 0.,
 8063                                    s: 0.,
 8064                                    l: 0.,
 8065                                    a: 0.4,
 8066                                },
 8067                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8068                                spread_radius: px(0.),
 8069                                offset: point(px(0.0), px(0.0)),
 8070                            }])
 8071                        }),
 8072                })
 8073                .on_mouse_move(|_e, _, cx| {
 8074                    cx.stop_propagation();
 8075                })
 8076                .size_full()
 8077                .child(element),
 8078        )
 8079        .map(|div| match decorations {
 8080            Decorations::Server => div,
 8081            Decorations::Client { tiling, .. } => div.child(
 8082                canvas(
 8083                    |_bounds, window, _| {
 8084                        window.insert_hitbox(
 8085                            Bounds::new(
 8086                                point(px(0.0), px(0.0)),
 8087                                window.window_bounds().get_bounds().size,
 8088                            ),
 8089                            HitboxBehavior::Normal,
 8090                        )
 8091                    },
 8092                    move |_bounds, hitbox, window, cx| {
 8093                        let mouse = window.mouse_position();
 8094                        let size = window.window_bounds().get_bounds().size;
 8095                        let Some(edge) =
 8096                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8097                        else {
 8098                            return;
 8099                        };
 8100                        cx.set_global(GlobalResizeEdge(edge));
 8101                        window.set_cursor_style(
 8102                            match edge {
 8103                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8104                                ResizeEdge::Left | ResizeEdge::Right => {
 8105                                    CursorStyle::ResizeLeftRight
 8106                                }
 8107                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8108                                    CursorStyle::ResizeUpLeftDownRight
 8109                                }
 8110                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8111                                    CursorStyle::ResizeUpRightDownLeft
 8112                                }
 8113                            },
 8114                            &hitbox,
 8115                        );
 8116                    },
 8117                )
 8118                .size_full()
 8119                .absolute(),
 8120            ),
 8121        })
 8122}
 8123
 8124fn resize_edge(
 8125    pos: Point<Pixels>,
 8126    shadow_size: Pixels,
 8127    window_size: Size<Pixels>,
 8128    tiling: Tiling,
 8129) -> Option<ResizeEdge> {
 8130    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8131    if bounds.contains(&pos) {
 8132        return None;
 8133    }
 8134
 8135    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8136    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8137    if !tiling.top && top_left_bounds.contains(&pos) {
 8138        return Some(ResizeEdge::TopLeft);
 8139    }
 8140
 8141    let top_right_bounds = Bounds::new(
 8142        Point::new(window_size.width - corner_size.width, px(0.)),
 8143        corner_size,
 8144    );
 8145    if !tiling.top && top_right_bounds.contains(&pos) {
 8146        return Some(ResizeEdge::TopRight);
 8147    }
 8148
 8149    let bottom_left_bounds = Bounds::new(
 8150        Point::new(px(0.), window_size.height - corner_size.height),
 8151        corner_size,
 8152    );
 8153    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8154        return Some(ResizeEdge::BottomLeft);
 8155    }
 8156
 8157    let bottom_right_bounds = Bounds::new(
 8158        Point::new(
 8159            window_size.width - corner_size.width,
 8160            window_size.height - corner_size.height,
 8161        ),
 8162        corner_size,
 8163    );
 8164    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8165        return Some(ResizeEdge::BottomRight);
 8166    }
 8167
 8168    if !tiling.top && pos.y < shadow_size {
 8169        Some(ResizeEdge::Top)
 8170    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8171        Some(ResizeEdge::Bottom)
 8172    } else if !tiling.left && pos.x < shadow_size {
 8173        Some(ResizeEdge::Left)
 8174    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8175        Some(ResizeEdge::Right)
 8176    } else {
 8177        None
 8178    }
 8179}
 8180
 8181fn join_pane_into_active(
 8182    active_pane: &Entity<Pane>,
 8183    pane: &Entity<Pane>,
 8184    window: &mut Window,
 8185    cx: &mut App,
 8186) {
 8187    if pane == active_pane {
 8188    } else if pane.read(cx).items_len() == 0 {
 8189        pane.update(cx, |_, cx| {
 8190            cx.emit(pane::Event::Remove {
 8191                focus_on_pane: None,
 8192            });
 8193        })
 8194    } else {
 8195        move_all_items(pane, active_pane, window, cx);
 8196    }
 8197}
 8198
 8199fn move_all_items(
 8200    from_pane: &Entity<Pane>,
 8201    to_pane: &Entity<Pane>,
 8202    window: &mut Window,
 8203    cx: &mut App,
 8204) {
 8205    let destination_is_different = from_pane != to_pane;
 8206    let mut moved_items = 0;
 8207    for (item_ix, item_handle) in from_pane
 8208        .read(cx)
 8209        .items()
 8210        .enumerate()
 8211        .map(|(ix, item)| (ix, item.clone()))
 8212        .collect::<Vec<_>>()
 8213    {
 8214        let ix = item_ix - moved_items;
 8215        if destination_is_different {
 8216            // Close item from previous pane
 8217            from_pane.update(cx, |source, cx| {
 8218                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8219            });
 8220            moved_items += 1;
 8221        }
 8222
 8223        // This automatically removes duplicate items in the pane
 8224        to_pane.update(cx, |destination, cx| {
 8225            destination.add_item(item_handle, true, true, None, window, cx);
 8226            window.focus(&destination.focus_handle(cx))
 8227        });
 8228    }
 8229}
 8230
 8231pub fn move_item(
 8232    source: &Entity<Pane>,
 8233    destination: &Entity<Pane>,
 8234    item_id_to_move: EntityId,
 8235    destination_index: usize,
 8236    activate: bool,
 8237    window: &mut Window,
 8238    cx: &mut App,
 8239) {
 8240    let Some((item_ix, item_handle)) = source
 8241        .read(cx)
 8242        .items()
 8243        .enumerate()
 8244        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8245        .map(|(ix, item)| (ix, item.clone()))
 8246    else {
 8247        // Tab was closed during drag
 8248        return;
 8249    };
 8250
 8251    if source != destination {
 8252        // Close item from previous pane
 8253        source.update(cx, |source, cx| {
 8254            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8255        });
 8256    }
 8257
 8258    // This automatically removes duplicate items in the pane
 8259    destination.update(cx, |destination, cx| {
 8260        destination.add_item_inner(
 8261            item_handle,
 8262            activate,
 8263            activate,
 8264            activate,
 8265            Some(destination_index),
 8266            window,
 8267            cx,
 8268        );
 8269        if activate {
 8270            window.focus(&destination.focus_handle(cx))
 8271        }
 8272    });
 8273}
 8274
 8275pub fn move_active_item(
 8276    source: &Entity<Pane>,
 8277    destination: &Entity<Pane>,
 8278    focus_destination: bool,
 8279    close_if_empty: bool,
 8280    window: &mut Window,
 8281    cx: &mut App,
 8282) {
 8283    if source == destination {
 8284        return;
 8285    }
 8286    let Some(active_item) = source.read(cx).active_item() else {
 8287        return;
 8288    };
 8289    source.update(cx, |source_pane, cx| {
 8290        let item_id = active_item.item_id();
 8291        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8292        destination.update(cx, |target_pane, cx| {
 8293            target_pane.add_item(
 8294                active_item,
 8295                focus_destination,
 8296                focus_destination,
 8297                Some(target_pane.items_len()),
 8298                window,
 8299                cx,
 8300            );
 8301        });
 8302    });
 8303}
 8304
 8305pub fn clone_active_item(
 8306    workspace_id: Option<WorkspaceId>,
 8307    source: &Entity<Pane>,
 8308    destination: &Entity<Pane>,
 8309    focus_destination: bool,
 8310    window: &mut Window,
 8311    cx: &mut App,
 8312) {
 8313    if source == destination {
 8314        return;
 8315    }
 8316    let Some(active_item) = source.read(cx).active_item() else {
 8317        return;
 8318    };
 8319    if !active_item.can_split(cx) {
 8320        return;
 8321    }
 8322    let destination = destination.downgrade();
 8323    let task = active_item.clone_on_split(workspace_id, window, cx);
 8324    window
 8325        .spawn(cx, async move |cx| {
 8326            let Some(clone) = task.await else {
 8327                return;
 8328            };
 8329            destination
 8330                .update_in(cx, |target_pane, window, cx| {
 8331                    target_pane.add_item(
 8332                        clone,
 8333                        focus_destination,
 8334                        focus_destination,
 8335                        Some(target_pane.items_len()),
 8336                        window,
 8337                        cx,
 8338                    );
 8339                })
 8340                .log_err();
 8341        })
 8342        .detach();
 8343}
 8344
 8345#[derive(Debug)]
 8346pub struct WorkspacePosition {
 8347    pub window_bounds: Option<WindowBounds>,
 8348    pub display: Option<Uuid>,
 8349    pub centered_layout: bool,
 8350}
 8351
 8352pub fn remote_workspace_position_from_db(
 8353    connection_options: RemoteConnectionOptions,
 8354    paths_to_open: &[PathBuf],
 8355    cx: &App,
 8356) -> Task<Result<WorkspacePosition>> {
 8357    let paths = paths_to_open.to_vec();
 8358
 8359    cx.background_spawn(async move {
 8360        let remote_connection_id = persistence::DB
 8361            .get_or_create_remote_connection(connection_options)
 8362            .await
 8363            .context("fetching serialized ssh project")?;
 8364        let serialized_workspace =
 8365            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8366
 8367        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8368            (Some(WindowBounds::Windowed(bounds)), None)
 8369        } else {
 8370            let restorable_bounds = serialized_workspace
 8371                .as_ref()
 8372                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8373                .or_else(|| {
 8374                    let (display, window_bounds) = DB.last_window().log_err()?;
 8375                    Some((display?, window_bounds?))
 8376                });
 8377
 8378            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8379                (Some(serialized_status.0), Some(serialized_display))
 8380            } else {
 8381                (None, None)
 8382            }
 8383        };
 8384
 8385        let centered_layout = serialized_workspace
 8386            .as_ref()
 8387            .map(|w| w.centered_layout)
 8388            .unwrap_or(false);
 8389
 8390        Ok(WorkspacePosition {
 8391            window_bounds,
 8392            display,
 8393            centered_layout,
 8394        })
 8395    })
 8396}
 8397
 8398pub fn with_active_or_new_workspace(
 8399    cx: &mut App,
 8400    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8401) {
 8402    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8403        Some(workspace) => {
 8404            cx.defer(move |cx| {
 8405                workspace
 8406                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8407                    .log_err();
 8408            });
 8409        }
 8410        None => {
 8411            let app_state = AppState::global(cx);
 8412            if let Some(app_state) = app_state.upgrade() {
 8413                open_new(
 8414                    OpenOptions::default(),
 8415                    app_state,
 8416                    cx,
 8417                    move |workspace, window, cx| f(workspace, window, cx),
 8418                )
 8419                .detach_and_log_err(cx);
 8420            }
 8421        }
 8422    }
 8423}
 8424
 8425#[cfg(test)]
 8426mod tests {
 8427    use std::{cell::RefCell, rc::Rc};
 8428
 8429    use super::*;
 8430    use crate::{
 8431        dock::{PanelEvent, test::TestPanel},
 8432        item::{
 8433            ItemBufferKind, ItemEvent,
 8434            test::{TestItem, TestProjectItem},
 8435        },
 8436    };
 8437    use fs::FakeFs;
 8438    use gpui::{
 8439        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8440        UpdateGlobal, VisualTestContext, px,
 8441    };
 8442    use project::{Project, ProjectEntryId};
 8443    use serde_json::json;
 8444    use settings::SettingsStore;
 8445    use util::rel_path::rel_path;
 8446
 8447    #[gpui::test]
 8448    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8449        init_test(cx);
 8450
 8451        let fs = FakeFs::new(cx.executor());
 8452        let project = Project::test(fs, [], cx).await;
 8453        let (workspace, cx) =
 8454            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8455
 8456        // Adding an item with no ambiguity renders the tab without detail.
 8457        let item1 = cx.new(|cx| {
 8458            let mut item = TestItem::new(cx);
 8459            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8460            item
 8461        });
 8462        workspace.update_in(cx, |workspace, window, cx| {
 8463            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8464        });
 8465        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8466
 8467        // Adding an item that creates ambiguity increases the level of detail on
 8468        // both tabs.
 8469        let item2 = cx.new_window_entity(|_window, cx| {
 8470            let mut item = TestItem::new(cx);
 8471            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8472            item
 8473        });
 8474        workspace.update_in(cx, |workspace, window, cx| {
 8475            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8476        });
 8477        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8478        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8479
 8480        // Adding an item that creates ambiguity increases the level of detail only
 8481        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8482        // we stop at the highest detail available.
 8483        let item3 = cx.new(|cx| {
 8484            let mut item = TestItem::new(cx);
 8485            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8486            item
 8487        });
 8488        workspace.update_in(cx, |workspace, window, cx| {
 8489            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8490        });
 8491        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8492        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8493        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8494    }
 8495
 8496    #[gpui::test]
 8497    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8498        init_test(cx);
 8499
 8500        let fs = FakeFs::new(cx.executor());
 8501        fs.insert_tree(
 8502            "/root1",
 8503            json!({
 8504                "one.txt": "",
 8505                "two.txt": "",
 8506            }),
 8507        )
 8508        .await;
 8509        fs.insert_tree(
 8510            "/root2",
 8511            json!({
 8512                "three.txt": "",
 8513            }),
 8514        )
 8515        .await;
 8516
 8517        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8518        let (workspace, cx) =
 8519            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8520        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8521        let worktree_id = project.update(cx, |project, cx| {
 8522            project.worktrees(cx).next().unwrap().read(cx).id()
 8523        });
 8524
 8525        let item1 = cx.new(|cx| {
 8526            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8527        });
 8528        let item2 = cx.new(|cx| {
 8529            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8530        });
 8531
 8532        // Add an item to an empty pane
 8533        workspace.update_in(cx, |workspace, window, cx| {
 8534            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8535        });
 8536        project.update(cx, |project, cx| {
 8537            assert_eq!(
 8538                project.active_entry(),
 8539                project
 8540                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8541                    .map(|e| e.id)
 8542            );
 8543        });
 8544        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8545
 8546        // Add a second item to a non-empty pane
 8547        workspace.update_in(cx, |workspace, window, cx| {
 8548            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8549        });
 8550        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8551        project.update(cx, |project, cx| {
 8552            assert_eq!(
 8553                project.active_entry(),
 8554                project
 8555                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 8556                    .map(|e| e.id)
 8557            );
 8558        });
 8559
 8560        // Close the active item
 8561        pane.update_in(cx, |pane, window, cx| {
 8562            pane.close_active_item(&Default::default(), window, cx)
 8563        })
 8564        .await
 8565        .unwrap();
 8566        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8567        project.update(cx, |project, cx| {
 8568            assert_eq!(
 8569                project.active_entry(),
 8570                project
 8571                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8572                    .map(|e| e.id)
 8573            );
 8574        });
 8575
 8576        // Add a project folder
 8577        project
 8578            .update(cx, |project, cx| {
 8579                project.find_or_create_worktree("root2", true, cx)
 8580            })
 8581            .await
 8582            .unwrap();
 8583        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8584
 8585        // Remove a project folder
 8586        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8587        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8588    }
 8589
 8590    #[gpui::test]
 8591    async fn test_close_window(cx: &mut TestAppContext) {
 8592        init_test(cx);
 8593
 8594        let fs = FakeFs::new(cx.executor());
 8595        fs.insert_tree("/root", json!({ "one": "" })).await;
 8596
 8597        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8598        let (workspace, cx) =
 8599            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8600
 8601        // When there are no dirty items, there's nothing to do.
 8602        let item1 = cx.new(TestItem::new);
 8603        workspace.update_in(cx, |w, window, cx| {
 8604            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8605        });
 8606        let task = workspace.update_in(cx, |w, window, cx| {
 8607            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8608        });
 8609        assert!(task.await.unwrap());
 8610
 8611        // When there are dirty untitled items, prompt to save each one. If the user
 8612        // cancels any prompt, then abort.
 8613        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8614        let item3 = cx.new(|cx| {
 8615            TestItem::new(cx)
 8616                .with_dirty(true)
 8617                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8618        });
 8619        workspace.update_in(cx, |w, window, cx| {
 8620            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8621            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8622        });
 8623        let task = workspace.update_in(cx, |w, window, cx| {
 8624            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8625        });
 8626        cx.executor().run_until_parked();
 8627        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8628        cx.executor().run_until_parked();
 8629        assert!(!cx.has_pending_prompt());
 8630        assert!(!task.await.unwrap());
 8631    }
 8632
 8633    #[gpui::test]
 8634    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8635        init_test(cx);
 8636
 8637        // Register TestItem as a serializable item
 8638        cx.update(|cx| {
 8639            register_serializable_item::<TestItem>(cx);
 8640        });
 8641
 8642        let fs = FakeFs::new(cx.executor());
 8643        fs.insert_tree("/root", json!({ "one": "" })).await;
 8644
 8645        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8646        let (workspace, cx) =
 8647            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8648
 8649        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8650        let item1 = cx.new(|cx| {
 8651            TestItem::new(cx)
 8652                .with_dirty(true)
 8653                .with_serialize(|| Some(Task::ready(Ok(()))))
 8654        });
 8655        let item2 = cx.new(|cx| {
 8656            TestItem::new(cx)
 8657                .with_dirty(true)
 8658                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8659                .with_serialize(|| Some(Task::ready(Ok(()))))
 8660        });
 8661        workspace.update_in(cx, |w, window, cx| {
 8662            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8663            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8664        });
 8665        let task = workspace.update_in(cx, |w, window, cx| {
 8666            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8667        });
 8668        assert!(task.await.unwrap());
 8669    }
 8670
 8671    #[gpui::test]
 8672    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8673        init_test(cx);
 8674
 8675        let fs = FakeFs::new(cx.executor());
 8676
 8677        let project = Project::test(fs, None, cx).await;
 8678        let (workspace, cx) =
 8679            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8680
 8681        let item1 = cx.new(|cx| {
 8682            TestItem::new(cx)
 8683                .with_dirty(true)
 8684                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8685        });
 8686        let item2 = cx.new(|cx| {
 8687            TestItem::new(cx)
 8688                .with_dirty(true)
 8689                .with_conflict(true)
 8690                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8691        });
 8692        let item3 = cx.new(|cx| {
 8693            TestItem::new(cx)
 8694                .with_dirty(true)
 8695                .with_conflict(true)
 8696                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8697        });
 8698        let item4 = cx.new(|cx| {
 8699            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8700                let project_item = TestProjectItem::new_untitled(cx);
 8701                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8702                project_item
 8703            }])
 8704        });
 8705        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8706            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8707            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8708            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8709            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8710            workspace.active_pane().clone()
 8711        });
 8712
 8713        let close_items = pane.update_in(cx, |pane, window, cx| {
 8714            pane.activate_item(1, true, true, window, cx);
 8715            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8716            let item1_id = item1.item_id();
 8717            let item3_id = item3.item_id();
 8718            let item4_id = item4.item_id();
 8719            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8720                [item1_id, item3_id, item4_id].contains(&id)
 8721            })
 8722        });
 8723        cx.executor().run_until_parked();
 8724
 8725        assert!(cx.has_pending_prompt());
 8726        cx.simulate_prompt_answer("Save all");
 8727
 8728        cx.executor().run_until_parked();
 8729
 8730        // Item 1 is saved. There's a prompt to save item 3.
 8731        pane.update(cx, |pane, cx| {
 8732            assert_eq!(item1.read(cx).save_count, 1);
 8733            assert_eq!(item1.read(cx).save_as_count, 0);
 8734            assert_eq!(item1.read(cx).reload_count, 0);
 8735            assert_eq!(pane.items_len(), 3);
 8736            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8737        });
 8738        assert!(cx.has_pending_prompt());
 8739
 8740        // Cancel saving item 3.
 8741        cx.simulate_prompt_answer("Discard");
 8742        cx.executor().run_until_parked();
 8743
 8744        // Item 3 is reloaded. There's a prompt to save item 4.
 8745        pane.update(cx, |pane, cx| {
 8746            assert_eq!(item3.read(cx).save_count, 0);
 8747            assert_eq!(item3.read(cx).save_as_count, 0);
 8748            assert_eq!(item3.read(cx).reload_count, 1);
 8749            assert_eq!(pane.items_len(), 2);
 8750            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8751        });
 8752
 8753        // There's a prompt for a path for item 4.
 8754        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8755        close_items.await.unwrap();
 8756
 8757        // The requested items are closed.
 8758        pane.update(cx, |pane, cx| {
 8759            assert_eq!(item4.read(cx).save_count, 0);
 8760            assert_eq!(item4.read(cx).save_as_count, 1);
 8761            assert_eq!(item4.read(cx).reload_count, 0);
 8762            assert_eq!(pane.items_len(), 1);
 8763            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8764        });
 8765    }
 8766
 8767    #[gpui::test]
 8768    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8769        init_test(cx);
 8770
 8771        let fs = FakeFs::new(cx.executor());
 8772        let project = Project::test(fs, [], cx).await;
 8773        let (workspace, cx) =
 8774            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8775
 8776        // Create several workspace items with single project entries, and two
 8777        // workspace items with multiple project entries.
 8778        let single_entry_items = (0..=4)
 8779            .map(|project_entry_id| {
 8780                cx.new(|cx| {
 8781                    TestItem::new(cx)
 8782                        .with_dirty(true)
 8783                        .with_project_items(&[dirty_project_item(
 8784                            project_entry_id,
 8785                            &format!("{project_entry_id}.txt"),
 8786                            cx,
 8787                        )])
 8788                })
 8789            })
 8790            .collect::<Vec<_>>();
 8791        let item_2_3 = cx.new(|cx| {
 8792            TestItem::new(cx)
 8793                .with_dirty(true)
 8794                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8795                .with_project_items(&[
 8796                    single_entry_items[2].read(cx).project_items[0].clone(),
 8797                    single_entry_items[3].read(cx).project_items[0].clone(),
 8798                ])
 8799        });
 8800        let item_3_4 = cx.new(|cx| {
 8801            TestItem::new(cx)
 8802                .with_dirty(true)
 8803                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8804                .with_project_items(&[
 8805                    single_entry_items[3].read(cx).project_items[0].clone(),
 8806                    single_entry_items[4].read(cx).project_items[0].clone(),
 8807                ])
 8808        });
 8809
 8810        // Create two panes that contain the following project entries:
 8811        //   left pane:
 8812        //     multi-entry items:   (2, 3)
 8813        //     single-entry items:  0, 2, 3, 4
 8814        //   right pane:
 8815        //     single-entry items:  4, 1
 8816        //     multi-entry items:   (3, 4)
 8817        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8818            let left_pane = workspace.active_pane().clone();
 8819            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8820            workspace.add_item_to_active_pane(
 8821                single_entry_items[0].boxed_clone(),
 8822                None,
 8823                true,
 8824                window,
 8825                cx,
 8826            );
 8827            workspace.add_item_to_active_pane(
 8828                single_entry_items[2].boxed_clone(),
 8829                None,
 8830                true,
 8831                window,
 8832                cx,
 8833            );
 8834            workspace.add_item_to_active_pane(
 8835                single_entry_items[3].boxed_clone(),
 8836                None,
 8837                true,
 8838                window,
 8839                cx,
 8840            );
 8841            workspace.add_item_to_active_pane(
 8842                single_entry_items[4].boxed_clone(),
 8843                None,
 8844                true,
 8845                window,
 8846                cx,
 8847            );
 8848
 8849            let right_pane =
 8850                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 8851
 8852            let boxed_clone = single_entry_items[1].boxed_clone();
 8853            let right_pane = window.spawn(cx, async move |cx| {
 8854                right_pane.await.inspect(|right_pane| {
 8855                    right_pane
 8856                        .update_in(cx, |pane, window, cx| {
 8857                            pane.add_item(boxed_clone, true, true, None, window, cx);
 8858                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8859                        })
 8860                        .unwrap();
 8861                })
 8862            });
 8863
 8864            (left_pane, right_pane)
 8865        });
 8866        let right_pane = right_pane.await.unwrap();
 8867        cx.focus(&right_pane);
 8868
 8869        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8870            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8871                .unwrap()
 8872        });
 8873        cx.executor().run_until_parked();
 8874
 8875        let msg = cx.pending_prompt().unwrap().0;
 8876        assert!(msg.contains("1.txt"));
 8877        assert!(!msg.contains("2.txt"));
 8878        assert!(!msg.contains("3.txt"));
 8879        assert!(!msg.contains("4.txt"));
 8880
 8881        cx.simulate_prompt_answer("Cancel");
 8882        close.await;
 8883
 8884        left_pane
 8885            .update_in(cx, |left_pane, window, cx| {
 8886                left_pane.close_item_by_id(
 8887                    single_entry_items[3].entity_id(),
 8888                    SaveIntent::Skip,
 8889                    window,
 8890                    cx,
 8891                )
 8892            })
 8893            .await
 8894            .unwrap();
 8895
 8896        close = right_pane.update_in(cx, |pane, window, cx| {
 8897            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8898                .unwrap()
 8899        });
 8900        cx.executor().run_until_parked();
 8901
 8902        let details = cx.pending_prompt().unwrap().1;
 8903        assert!(details.contains("1.txt"));
 8904        assert!(!details.contains("2.txt"));
 8905        assert!(details.contains("3.txt"));
 8906        // ideally this assertion could be made, but today we can only
 8907        // save whole items not project items, so the orphaned item 3 causes
 8908        // 4 to be saved too.
 8909        // assert!(!details.contains("4.txt"));
 8910
 8911        cx.simulate_prompt_answer("Save all");
 8912
 8913        cx.executor().run_until_parked();
 8914        close.await;
 8915        right_pane.read_with(cx, |pane, _| {
 8916            assert_eq!(pane.items_len(), 0);
 8917        });
 8918    }
 8919
 8920    #[gpui::test]
 8921    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8922        init_test(cx);
 8923
 8924        let fs = FakeFs::new(cx.executor());
 8925        let project = Project::test(fs, [], cx).await;
 8926        let (workspace, cx) =
 8927            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8928        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8929
 8930        let item = cx.new(|cx| {
 8931            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8932        });
 8933        let item_id = item.entity_id();
 8934        workspace.update_in(cx, |workspace, window, cx| {
 8935            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8936        });
 8937
 8938        // Autosave on window change.
 8939        item.update(cx, |item, cx| {
 8940            SettingsStore::update_global(cx, |settings, cx| {
 8941                settings.update_user_settings(cx, |settings| {
 8942                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 8943                })
 8944            });
 8945            item.is_dirty = true;
 8946        });
 8947
 8948        // Deactivating the window saves the file.
 8949        cx.deactivate_window();
 8950        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8951
 8952        // Re-activating the window doesn't save the file.
 8953        cx.update(|window, _| window.activate_window());
 8954        cx.executor().run_until_parked();
 8955        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8956
 8957        // Autosave on focus change.
 8958        item.update_in(cx, |item, window, cx| {
 8959            cx.focus_self(window);
 8960            SettingsStore::update_global(cx, |settings, cx| {
 8961                settings.update_user_settings(cx, |settings| {
 8962                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 8963                })
 8964            });
 8965            item.is_dirty = true;
 8966        });
 8967        // Blurring the item saves the file.
 8968        item.update_in(cx, |_, window, _| window.blur());
 8969        cx.executor().run_until_parked();
 8970        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8971
 8972        // Deactivating the window still saves the file.
 8973        item.update_in(cx, |item, window, cx| {
 8974            cx.focus_self(window);
 8975            item.is_dirty = true;
 8976        });
 8977        cx.deactivate_window();
 8978        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8979
 8980        // Autosave after delay.
 8981        item.update(cx, |item, cx| {
 8982            SettingsStore::update_global(cx, |settings, cx| {
 8983                settings.update_user_settings(cx, |settings| {
 8984                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 8985                        milliseconds: 500.into(),
 8986                    });
 8987                })
 8988            });
 8989            item.is_dirty = true;
 8990            cx.emit(ItemEvent::Edit);
 8991        });
 8992
 8993        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8994        cx.executor().advance_clock(Duration::from_millis(250));
 8995        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8996
 8997        // After delay expires, the file is saved.
 8998        cx.executor().advance_clock(Duration::from_millis(250));
 8999        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9000
 9001        // Autosave after delay, should save earlier than delay if tab is closed
 9002        item.update(cx, |item, cx| {
 9003            item.is_dirty = true;
 9004            cx.emit(ItemEvent::Edit);
 9005        });
 9006        cx.executor().advance_clock(Duration::from_millis(250));
 9007        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9008
 9009        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9010        pane.update_in(cx, |pane, window, cx| {
 9011            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9012        })
 9013        .await
 9014        .unwrap();
 9015        assert!(!cx.has_pending_prompt());
 9016        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9017
 9018        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9019        workspace.update_in(cx, |workspace, window, cx| {
 9020            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9021        });
 9022        item.update_in(cx, |item, _window, cx| {
 9023            item.is_dirty = true;
 9024            for project_item in &mut item.project_items {
 9025                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9026            }
 9027        });
 9028        cx.run_until_parked();
 9029        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9030
 9031        // Autosave on focus change, ensuring closing the tab counts as such.
 9032        item.update(cx, |item, cx| {
 9033            SettingsStore::update_global(cx, |settings, cx| {
 9034                settings.update_user_settings(cx, |settings| {
 9035                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9036                })
 9037            });
 9038            item.is_dirty = true;
 9039            for project_item in &mut item.project_items {
 9040                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9041            }
 9042        });
 9043
 9044        pane.update_in(cx, |pane, window, cx| {
 9045            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9046        })
 9047        .await
 9048        .unwrap();
 9049        assert!(!cx.has_pending_prompt());
 9050        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9051
 9052        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9053        workspace.update_in(cx, |workspace, window, cx| {
 9054            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9055        });
 9056        item.update_in(cx, |item, window, cx| {
 9057            item.project_items[0].update(cx, |item, _| {
 9058                item.entry_id = None;
 9059            });
 9060            item.is_dirty = true;
 9061            window.blur();
 9062        });
 9063        cx.run_until_parked();
 9064        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9065
 9066        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9067        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9068            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9069        });
 9070        cx.run_until_parked();
 9071        assert!(cx.has_pending_prompt());
 9072        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9073    }
 9074
 9075    #[gpui::test]
 9076    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9077        init_test(cx);
 9078
 9079        let fs = FakeFs::new(cx.executor());
 9080
 9081        let project = Project::test(fs, [], cx).await;
 9082        let (workspace, cx) =
 9083            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9084
 9085        let item = cx.new(|cx| {
 9086            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9087        });
 9088        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9089        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9090        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9091
 9092        workspace.update_in(cx, |workspace, window, cx| {
 9093            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9094            let toolbar_notification_count = toolbar_notify_count.clone();
 9095            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9096                *toolbar_notification_count.borrow_mut() += 1
 9097            })
 9098            .detach();
 9099        });
 9100
 9101        pane.read_with(cx, |pane, _| {
 9102            assert!(!pane.can_navigate_backward());
 9103            assert!(!pane.can_navigate_forward());
 9104        });
 9105
 9106        item.update_in(cx, |item, _, cx| {
 9107            item.set_state("one".to_string(), cx);
 9108        });
 9109
 9110        // Toolbar must be notified to re-render the navigation buttons
 9111        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9112
 9113        pane.read_with(cx, |pane, _| {
 9114            assert!(pane.can_navigate_backward());
 9115            assert!(!pane.can_navigate_forward());
 9116        });
 9117
 9118        workspace
 9119            .update_in(cx, |workspace, window, cx| {
 9120                workspace.go_back(pane.downgrade(), window, cx)
 9121            })
 9122            .await
 9123            .unwrap();
 9124
 9125        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9126        pane.read_with(cx, |pane, _| {
 9127            assert!(!pane.can_navigate_backward());
 9128            assert!(pane.can_navigate_forward());
 9129        });
 9130    }
 9131
 9132    #[gpui::test]
 9133    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9134        init_test(cx);
 9135        let fs = FakeFs::new(cx.executor());
 9136
 9137        let project = Project::test(fs, [], cx).await;
 9138        let (workspace, cx) =
 9139            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9140
 9141        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9142            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9143            workspace.add_panel(panel.clone(), window, cx);
 9144
 9145            workspace
 9146                .right_dock()
 9147                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9148
 9149            panel
 9150        });
 9151
 9152        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9153        pane.update_in(cx, |pane, window, cx| {
 9154            let item = cx.new(TestItem::new);
 9155            pane.add_item(Box::new(item), true, true, None, window, cx);
 9156        });
 9157
 9158        // Transfer focus from center to panel
 9159        workspace.update_in(cx, |workspace, window, cx| {
 9160            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9161        });
 9162
 9163        workspace.update_in(cx, |workspace, window, cx| {
 9164            assert!(workspace.right_dock().read(cx).is_open());
 9165            assert!(!panel.is_zoomed(window, cx));
 9166            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9167        });
 9168
 9169        // Transfer focus from panel to center
 9170        workspace.update_in(cx, |workspace, window, cx| {
 9171            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9172        });
 9173
 9174        workspace.update_in(cx, |workspace, window, cx| {
 9175            assert!(workspace.right_dock().read(cx).is_open());
 9176            assert!(!panel.is_zoomed(window, cx));
 9177            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9178        });
 9179
 9180        // Close the dock
 9181        workspace.update_in(cx, |workspace, window, cx| {
 9182            workspace.toggle_dock(DockPosition::Right, window, cx);
 9183        });
 9184
 9185        workspace.update_in(cx, |workspace, window, cx| {
 9186            assert!(!workspace.right_dock().read(cx).is_open());
 9187            assert!(!panel.is_zoomed(window, cx));
 9188            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9189        });
 9190
 9191        // Open the dock
 9192        workspace.update_in(cx, |workspace, window, cx| {
 9193            workspace.toggle_dock(DockPosition::Right, window, cx);
 9194        });
 9195
 9196        workspace.update_in(cx, |workspace, window, cx| {
 9197            assert!(workspace.right_dock().read(cx).is_open());
 9198            assert!(!panel.is_zoomed(window, cx));
 9199            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9200        });
 9201
 9202        // Focus and zoom panel
 9203        panel.update_in(cx, |panel, window, cx| {
 9204            cx.focus_self(window);
 9205            panel.set_zoomed(true, window, cx)
 9206        });
 9207
 9208        workspace.update_in(cx, |workspace, window, cx| {
 9209            assert!(workspace.right_dock().read(cx).is_open());
 9210            assert!(panel.is_zoomed(window, cx));
 9211            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9212        });
 9213
 9214        // Transfer focus to the center closes the dock
 9215        workspace.update_in(cx, |workspace, window, cx| {
 9216            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9217        });
 9218
 9219        workspace.update_in(cx, |workspace, window, cx| {
 9220            assert!(!workspace.right_dock().read(cx).is_open());
 9221            assert!(panel.is_zoomed(window, cx));
 9222            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9223        });
 9224
 9225        // Transferring focus back to the panel keeps it zoomed
 9226        workspace.update_in(cx, |workspace, window, cx| {
 9227            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9228        });
 9229
 9230        workspace.update_in(cx, |workspace, window, cx| {
 9231            assert!(workspace.right_dock().read(cx).is_open());
 9232            assert!(panel.is_zoomed(window, cx));
 9233            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9234        });
 9235
 9236        // Close the dock while it is zoomed
 9237        workspace.update_in(cx, |workspace, window, cx| {
 9238            workspace.toggle_dock(DockPosition::Right, window, cx)
 9239        });
 9240
 9241        workspace.update_in(cx, |workspace, window, cx| {
 9242            assert!(!workspace.right_dock().read(cx).is_open());
 9243            assert!(panel.is_zoomed(window, cx));
 9244            assert!(workspace.zoomed.is_none());
 9245            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9246        });
 9247
 9248        // Opening the dock, when it's zoomed, retains focus
 9249        workspace.update_in(cx, |workspace, window, cx| {
 9250            workspace.toggle_dock(DockPosition::Right, window, cx)
 9251        });
 9252
 9253        workspace.update_in(cx, |workspace, window, cx| {
 9254            assert!(workspace.right_dock().read(cx).is_open());
 9255            assert!(panel.is_zoomed(window, cx));
 9256            assert!(workspace.zoomed.is_some());
 9257            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9258        });
 9259
 9260        // Unzoom and close the panel, zoom the active pane.
 9261        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9262        workspace.update_in(cx, |workspace, window, cx| {
 9263            workspace.toggle_dock(DockPosition::Right, window, cx)
 9264        });
 9265        pane.update_in(cx, |pane, window, cx| {
 9266            pane.toggle_zoom(&Default::default(), window, cx)
 9267        });
 9268
 9269        // Opening a dock unzooms the pane.
 9270        workspace.update_in(cx, |workspace, window, cx| {
 9271            workspace.toggle_dock(DockPosition::Right, window, cx)
 9272        });
 9273        workspace.update_in(cx, |workspace, window, cx| {
 9274            let pane = pane.read(cx);
 9275            assert!(!pane.is_zoomed());
 9276            assert!(!pane.focus_handle(cx).is_focused(window));
 9277            assert!(workspace.right_dock().read(cx).is_open());
 9278            assert!(workspace.zoomed.is_none());
 9279        });
 9280    }
 9281
 9282    #[gpui::test]
 9283    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
 9284        init_test(cx);
 9285        let fs = FakeFs::new(cx.executor());
 9286
 9287        let project = Project::test(fs, [], cx).await;
 9288        let (workspace, cx) =
 9289            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9290        workspace.update_in(cx, |workspace, window, cx| {
 9291            // Open two docks
 9292            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9293            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9294
 9295            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9296            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9297
 9298            assert!(left_dock.read(cx).is_open());
 9299            assert!(right_dock.read(cx).is_open());
 9300        });
 9301
 9302        workspace.update_in(cx, |workspace, window, cx| {
 9303            // Toggle all docks - should close both
 9304            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9305
 9306            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9307            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9308            assert!(!left_dock.read(cx).is_open());
 9309            assert!(!right_dock.read(cx).is_open());
 9310        });
 9311
 9312        workspace.update_in(cx, |workspace, window, cx| {
 9313            // Toggle again - should reopen both
 9314            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9315
 9316            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9317            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9318            assert!(left_dock.read(cx).is_open());
 9319            assert!(right_dock.read(cx).is_open());
 9320        });
 9321    }
 9322
 9323    #[gpui::test]
 9324    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
 9325        init_test(cx);
 9326        let fs = FakeFs::new(cx.executor());
 9327
 9328        let project = Project::test(fs, [], cx).await;
 9329        let (workspace, cx) =
 9330            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9331        workspace.update_in(cx, |workspace, window, cx| {
 9332            // Open two docks
 9333            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9334            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9335
 9336            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9337            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9338
 9339            assert!(left_dock.read(cx).is_open());
 9340            assert!(right_dock.read(cx).is_open());
 9341        });
 9342
 9343        workspace.update_in(cx, |workspace, window, cx| {
 9344            // Close them manually
 9345            workspace.toggle_dock(DockPosition::Left, window, cx);
 9346            workspace.toggle_dock(DockPosition::Right, window, cx);
 9347
 9348            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9349            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9350            assert!(!left_dock.read(cx).is_open());
 9351            assert!(!right_dock.read(cx).is_open());
 9352        });
 9353
 9354        workspace.update_in(cx, |workspace, window, cx| {
 9355            // Toggle all docks - only last closed (right dock) should reopen
 9356            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9357
 9358            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9359            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9360            assert!(!left_dock.read(cx).is_open());
 9361            assert!(right_dock.read(cx).is_open());
 9362        });
 9363    }
 9364
 9365    #[gpui::test]
 9366    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
 9367        init_test(cx);
 9368        let fs = FakeFs::new(cx.executor());
 9369        let project = Project::test(fs, [], cx).await;
 9370        let (workspace, cx) =
 9371            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9372
 9373        // Open two docks (left and right) with one panel each
 9374        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
 9375            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9376            workspace.add_panel(left_panel.clone(), window, cx);
 9377
 9378            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9379            workspace.add_panel(right_panel.clone(), window, cx);
 9380
 9381            workspace.toggle_dock(DockPosition::Left, window, cx);
 9382            workspace.toggle_dock(DockPosition::Right, window, cx);
 9383
 9384            // Verify initial state
 9385            assert!(
 9386                workspace.left_dock().read(cx).is_open(),
 9387                "Left dock should be open"
 9388            );
 9389            assert_eq!(
 9390                workspace
 9391                    .left_dock()
 9392                    .read(cx)
 9393                    .visible_panel()
 9394                    .unwrap()
 9395                    .panel_id(),
 9396                left_panel.panel_id(),
 9397                "Left panel should be visible in left dock"
 9398            );
 9399            assert!(
 9400                workspace.right_dock().read(cx).is_open(),
 9401                "Right dock should be open"
 9402            );
 9403            assert_eq!(
 9404                workspace
 9405                    .right_dock()
 9406                    .read(cx)
 9407                    .visible_panel()
 9408                    .unwrap()
 9409                    .panel_id(),
 9410                right_panel.panel_id(),
 9411                "Right panel should be visible in right dock"
 9412            );
 9413            assert!(
 9414                !workspace.bottom_dock().read(cx).is_open(),
 9415                "Bottom dock should be closed"
 9416            );
 9417
 9418            (left_panel, right_panel)
 9419        });
 9420
 9421        // Focus the left panel and move it to the next position (bottom dock)
 9422        workspace.update_in(cx, |workspace, window, cx| {
 9423            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
 9424            assert!(
 9425                left_panel.read(cx).focus_handle(cx).is_focused(window),
 9426                "Left panel should be focused"
 9427            );
 9428        });
 9429
 9430        cx.dispatch_action(MoveFocusedPanelToNextPosition);
 9431
 9432        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
 9433        workspace.update(cx, |workspace, cx| {
 9434            assert!(
 9435                !workspace.left_dock().read(cx).is_open(),
 9436                "Left dock should be closed"
 9437            );
 9438            assert!(
 9439                workspace.bottom_dock().read(cx).is_open(),
 9440                "Bottom dock should now be open"
 9441            );
 9442            assert_eq!(
 9443                left_panel.read(cx).position,
 9444                DockPosition::Bottom,
 9445                "Left panel should now be in the bottom dock"
 9446            );
 9447            assert_eq!(
 9448                workspace
 9449                    .bottom_dock()
 9450                    .read(cx)
 9451                    .visible_panel()
 9452                    .unwrap()
 9453                    .panel_id(),
 9454                left_panel.panel_id(),
 9455                "Left panel should be the visible panel in the bottom dock"
 9456            );
 9457        });
 9458
 9459        // Toggle all docks off
 9460        workspace.update_in(cx, |workspace, window, cx| {
 9461            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9462            assert!(
 9463                !workspace.left_dock().read(cx).is_open(),
 9464                "Left dock should be closed"
 9465            );
 9466            assert!(
 9467                !workspace.right_dock().read(cx).is_open(),
 9468                "Right dock should be closed"
 9469            );
 9470            assert!(
 9471                !workspace.bottom_dock().read(cx).is_open(),
 9472                "Bottom dock should be closed"
 9473            );
 9474        });
 9475
 9476        // Toggle all docks back on and verify positions are restored
 9477        workspace.update_in(cx, |workspace, window, cx| {
 9478            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9479            assert!(
 9480                !workspace.left_dock().read(cx).is_open(),
 9481                "Left dock should remain closed"
 9482            );
 9483            assert!(
 9484                workspace.right_dock().read(cx).is_open(),
 9485                "Right dock should remain open"
 9486            );
 9487            assert!(
 9488                workspace.bottom_dock().read(cx).is_open(),
 9489                "Bottom dock should remain open"
 9490            );
 9491            assert_eq!(
 9492                left_panel.read(cx).position,
 9493                DockPosition::Bottom,
 9494                "Left panel should remain in the bottom dock"
 9495            );
 9496            assert_eq!(
 9497                right_panel.read(cx).position,
 9498                DockPosition::Right,
 9499                "Right panel should remain in the right dock"
 9500            );
 9501            assert_eq!(
 9502                workspace
 9503                    .bottom_dock()
 9504                    .read(cx)
 9505                    .visible_panel()
 9506                    .unwrap()
 9507                    .panel_id(),
 9508                left_panel.panel_id(),
 9509                "Left panel should be the visible panel in the right dock"
 9510            );
 9511        });
 9512    }
 9513
 9514    #[gpui::test]
 9515    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 9516        init_test(cx);
 9517
 9518        let fs = FakeFs::new(cx.executor());
 9519
 9520        let project = Project::test(fs, None, cx).await;
 9521        let (workspace, cx) =
 9522            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9523
 9524        // Let's arrange the panes like this:
 9525        //
 9526        // +-----------------------+
 9527        // |         top           |
 9528        // +------+--------+-------+
 9529        // | left | center | right |
 9530        // +------+--------+-------+
 9531        // |        bottom         |
 9532        // +-----------------------+
 9533
 9534        let top_item = cx.new(|cx| {
 9535            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 9536        });
 9537        let bottom_item = cx.new(|cx| {
 9538            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 9539        });
 9540        let left_item = cx.new(|cx| {
 9541            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 9542        });
 9543        let right_item = cx.new(|cx| {
 9544            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 9545        });
 9546        let center_item = cx.new(|cx| {
 9547            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 9548        });
 9549
 9550        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9551            let top_pane_id = workspace.active_pane().entity_id();
 9552            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 9553            workspace.split_pane(
 9554                workspace.active_pane().clone(),
 9555                SplitDirection::Down,
 9556                window,
 9557                cx,
 9558            );
 9559            top_pane_id
 9560        });
 9561        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9562            let bottom_pane_id = workspace.active_pane().entity_id();
 9563            workspace.add_item_to_active_pane(
 9564                Box::new(bottom_item.clone()),
 9565                None,
 9566                false,
 9567                window,
 9568                cx,
 9569            );
 9570            workspace.split_pane(
 9571                workspace.active_pane().clone(),
 9572                SplitDirection::Up,
 9573                window,
 9574                cx,
 9575            );
 9576            bottom_pane_id
 9577        });
 9578        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9579            let left_pane_id = workspace.active_pane().entity_id();
 9580            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 9581            workspace.split_pane(
 9582                workspace.active_pane().clone(),
 9583                SplitDirection::Right,
 9584                window,
 9585                cx,
 9586            );
 9587            left_pane_id
 9588        });
 9589        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9590            let right_pane_id = workspace.active_pane().entity_id();
 9591            workspace.add_item_to_active_pane(
 9592                Box::new(right_item.clone()),
 9593                None,
 9594                false,
 9595                window,
 9596                cx,
 9597            );
 9598            workspace.split_pane(
 9599                workspace.active_pane().clone(),
 9600                SplitDirection::Left,
 9601                window,
 9602                cx,
 9603            );
 9604            right_pane_id
 9605        });
 9606        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9607            let center_pane_id = workspace.active_pane().entity_id();
 9608            workspace.add_item_to_active_pane(
 9609                Box::new(center_item.clone()),
 9610                None,
 9611                false,
 9612                window,
 9613                cx,
 9614            );
 9615            center_pane_id
 9616        });
 9617        cx.executor().run_until_parked();
 9618
 9619        workspace.update_in(cx, |workspace, window, cx| {
 9620            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9621
 9622            // Join into next from center pane into right
 9623            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9624        });
 9625
 9626        workspace.update_in(cx, |workspace, window, cx| {
 9627            let active_pane = workspace.active_pane();
 9628            assert_eq!(right_pane_id, active_pane.entity_id());
 9629            assert_eq!(2, active_pane.read(cx).items_len());
 9630            let item_ids_in_pane =
 9631                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9632            assert!(item_ids_in_pane.contains(¢er_item.item_id()));
 9633            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9634
 9635            // Join into next from right pane into bottom
 9636            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9637        });
 9638
 9639        workspace.update_in(cx, |workspace, window, cx| {
 9640            let active_pane = workspace.active_pane();
 9641            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9642            assert_eq!(3, active_pane.read(cx).items_len());
 9643            let item_ids_in_pane =
 9644                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9645            assert!(item_ids_in_pane.contains(¢er_item.item_id()));
 9646            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9647            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9648
 9649            // Join into next from bottom pane into left
 9650            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9651        });
 9652
 9653        workspace.update_in(cx, |workspace, window, cx| {
 9654            let active_pane = workspace.active_pane();
 9655            assert_eq!(left_pane_id, active_pane.entity_id());
 9656            assert_eq!(4, active_pane.read(cx).items_len());
 9657            let item_ids_in_pane =
 9658                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9659            assert!(item_ids_in_pane.contains(¢er_item.item_id()));
 9660            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9661            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9662            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9663
 9664            // Join into next from left pane into top
 9665            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9666        });
 9667
 9668        workspace.update_in(cx, |workspace, window, cx| {
 9669            let active_pane = workspace.active_pane();
 9670            assert_eq!(top_pane_id, active_pane.entity_id());
 9671            assert_eq!(5, active_pane.read(cx).items_len());
 9672            let item_ids_in_pane =
 9673                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9674            assert!(item_ids_in_pane.contains(¢er_item.item_id()));
 9675            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9676            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9677            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9678            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9679
 9680            // Single pane left: no-op
 9681            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9682        });
 9683
 9684        workspace.update(cx, |workspace, _cx| {
 9685            let active_pane = workspace.active_pane();
 9686            assert_eq!(top_pane_id, active_pane.entity_id());
 9687        });
 9688    }
 9689
 9690    fn add_an_item_to_active_pane(
 9691        cx: &mut VisualTestContext,
 9692        workspace: &Entity<Workspace>,
 9693        item_id: u64,
 9694    ) -> Entity<TestItem> {
 9695        let item = cx.new(|cx| {
 9696            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9697                item_id,
 9698                "item{item_id}.txt",
 9699                cx,
 9700            )])
 9701        });
 9702        workspace.update_in(cx, |workspace, window, cx| {
 9703            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9704        });
 9705        item
 9706    }
 9707
 9708    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9709        workspace.update_in(cx, |workspace, window, cx| {
 9710            workspace.split_pane(
 9711                workspace.active_pane().clone(),
 9712                SplitDirection::Right,
 9713                window,
 9714                cx,
 9715            )
 9716        })
 9717    }
 9718
 9719    #[gpui::test]
 9720    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9721        init_test(cx);
 9722        let fs = FakeFs::new(cx.executor());
 9723        let project = Project::test(fs, None, cx).await;
 9724        let (workspace, cx) =
 9725            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9726
 9727        add_an_item_to_active_pane(cx, &workspace, 1);
 9728        split_pane(cx, &workspace);
 9729        add_an_item_to_active_pane(cx, &workspace, 2);
 9730        split_pane(cx, &workspace); // empty pane
 9731        split_pane(cx, &workspace);
 9732        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9733
 9734        cx.executor().run_until_parked();
 9735
 9736        workspace.update(cx, |workspace, cx| {
 9737            let num_panes = workspace.panes().len();
 9738            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9739            let active_item = workspace
 9740                .active_pane()
 9741                .read(cx)
 9742                .active_item()
 9743                .expect("item is in focus");
 9744
 9745            assert_eq!(num_panes, 4);
 9746            assert_eq!(num_items_in_current_pane, 1);
 9747            assert_eq!(active_item.item_id(), last_item.item_id());
 9748        });
 9749
 9750        workspace.update_in(cx, |workspace, window, cx| {
 9751            workspace.join_all_panes(window, cx);
 9752        });
 9753
 9754        workspace.update(cx, |workspace, cx| {
 9755            let num_panes = workspace.panes().len();
 9756            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9757            let active_item = workspace
 9758                .active_pane()
 9759                .read(cx)
 9760                .active_item()
 9761                .expect("item is in focus");
 9762
 9763            assert_eq!(num_panes, 1);
 9764            assert_eq!(num_items_in_current_pane, 3);
 9765            assert_eq!(active_item.item_id(), last_item.item_id());
 9766        });
 9767    }
 9768    struct TestModal(FocusHandle);
 9769
 9770    impl TestModal {
 9771        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9772            Self(cx.focus_handle())
 9773        }
 9774    }
 9775
 9776    impl EventEmitter<DismissEvent> for TestModal {}
 9777
 9778    impl Focusable for TestModal {
 9779        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9780            self.0.clone()
 9781        }
 9782    }
 9783
 9784    impl ModalView for TestModal {}
 9785
 9786    impl Render for TestModal {
 9787        fn render(
 9788            &mut self,
 9789            _window: &mut Window,
 9790            _cx: &mut Context<TestModal>,
 9791        ) -> impl IntoElement {
 9792            div().track_focus(&self.0)
 9793        }
 9794    }
 9795
 9796    #[gpui::test]
 9797    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9798        init_test(cx);
 9799        let fs = FakeFs::new(cx.executor());
 9800
 9801        let project = Project::test(fs, [], cx).await;
 9802        let (workspace, cx) =
 9803            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9804
 9805        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9806            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9807            workspace.add_panel(panel_1.clone(), window, cx);
 9808            workspace.toggle_dock(DockPosition::Left, window, cx);
 9809            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9810            workspace.add_panel(panel_2.clone(), window, cx);
 9811            workspace.toggle_dock(DockPosition::Right, window, cx);
 9812
 9813            let left_dock = workspace.left_dock();
 9814            assert_eq!(
 9815                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9816                panel_1.panel_id()
 9817            );
 9818            assert_eq!(
 9819                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9820                panel_1.size(window, cx)
 9821            );
 9822
 9823            left_dock.update(cx, |left_dock, cx| {
 9824                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9825            });
 9826            assert_eq!(
 9827                workspace
 9828                    .right_dock()
 9829                    .read(cx)
 9830                    .visible_panel()
 9831                    .unwrap()
 9832                    .panel_id(),
 9833                panel_2.panel_id(),
 9834            );
 9835
 9836            (panel_1, panel_2)
 9837        });
 9838
 9839        // Move panel_1 to the right
 9840        panel_1.update_in(cx, |panel_1, window, cx| {
 9841            panel_1.set_position(DockPosition::Right, window, cx)
 9842        });
 9843
 9844        workspace.update_in(cx, |workspace, window, cx| {
 9845            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9846            // Since it was the only panel on the left, the left dock should now be closed.
 9847            assert!(!workspace.left_dock().read(cx).is_open());
 9848            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9849            let right_dock = workspace.right_dock();
 9850            assert_eq!(
 9851                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9852                panel_1.panel_id()
 9853            );
 9854            assert_eq!(
 9855                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9856                px(1337.)
 9857            );
 9858
 9859            // Now we move panel_2 to the left
 9860            panel_2.set_position(DockPosition::Left, window, cx);
 9861        });
 9862
 9863        workspace.update(cx, |workspace, cx| {
 9864            // Since panel_2 was not visible on the right, we don't open the left dock.
 9865            assert!(!workspace.left_dock().read(cx).is_open());
 9866            // And the right dock is unaffected in its displaying of panel_1
 9867            assert!(workspace.right_dock().read(cx).is_open());
 9868            assert_eq!(
 9869                workspace
 9870                    .right_dock()
 9871                    .read(cx)
 9872                    .visible_panel()
 9873                    .unwrap()
 9874                    .panel_id(),
 9875                panel_1.panel_id(),
 9876            );
 9877        });
 9878
 9879        // Move panel_1 back to the left
 9880        panel_1.update_in(cx, |panel_1, window, cx| {
 9881            panel_1.set_position(DockPosition::Left, window, cx)
 9882        });
 9883
 9884        workspace.update_in(cx, |workspace, window, cx| {
 9885            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9886            let left_dock = workspace.left_dock();
 9887            assert!(left_dock.read(cx).is_open());
 9888            assert_eq!(
 9889                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9890                panel_1.panel_id()
 9891            );
 9892            assert_eq!(
 9893                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9894                px(1337.)
 9895            );
 9896            // And the right dock should be closed as it no longer has any panels.
 9897            assert!(!workspace.right_dock().read(cx).is_open());
 9898
 9899            // Now we move panel_1 to the bottom
 9900            panel_1.set_position(DockPosition::Bottom, window, cx);
 9901        });
 9902
 9903        workspace.update_in(cx, |workspace, window, cx| {
 9904            // Since panel_1 was visible on the left, we close the left dock.
 9905            assert!(!workspace.left_dock().read(cx).is_open());
 9906            // The bottom dock is sized based on the panel's default size,
 9907            // since the panel orientation changed from vertical to horizontal.
 9908            let bottom_dock = workspace.bottom_dock();
 9909            assert_eq!(
 9910                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9911                panel_1.size(window, cx),
 9912            );
 9913            // Close bottom dock and move panel_1 back to the left.
 9914            bottom_dock.update(cx, |bottom_dock, cx| {
 9915                bottom_dock.set_open(false, window, cx)
 9916            });
 9917            panel_1.set_position(DockPosition::Left, window, cx);
 9918        });
 9919
 9920        // Emit activated event on panel 1
 9921        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9922
 9923        // Now the left dock is open and panel_1 is active and focused.
 9924        workspace.update_in(cx, |workspace, window, cx| {
 9925            let left_dock = workspace.left_dock();
 9926            assert!(left_dock.read(cx).is_open());
 9927            assert_eq!(
 9928                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9929                panel_1.panel_id(),
 9930            );
 9931            assert!(panel_1.focus_handle(cx).is_focused(window));
 9932        });
 9933
 9934        // Emit closed event on panel 2, which is not active
 9935        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9936
 9937        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9938        workspace.update(cx, |workspace, cx| {
 9939            let left_dock = workspace.left_dock();
 9940            assert!(left_dock.read(cx).is_open());
 9941            assert_eq!(
 9942                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9943                panel_1.panel_id(),
 9944            );
 9945        });
 9946
 9947        // Emitting a ZoomIn event shows the panel as zoomed.
 9948        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9949        workspace.read_with(cx, |workspace, _| {
 9950            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9951            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9952        });
 9953
 9954        // Move panel to another dock while it is zoomed
 9955        panel_1.update_in(cx, |panel, window, cx| {
 9956            panel.set_position(DockPosition::Right, window, cx)
 9957        });
 9958        workspace.read_with(cx, |workspace, _| {
 9959            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9960
 9961            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9962        });
 9963
 9964        // This is a helper for getting a:
 9965        // - valid focus on an element,
 9966        // - that isn't a part of the panes and panels system of the Workspace,
 9967        // - and doesn't trigger the 'on_focus_lost' API.
 9968        let focus_other_view = {
 9969            let workspace = workspace.clone();
 9970            move |cx: &mut VisualTestContext| {
 9971                workspace.update_in(cx, |workspace, window, cx| {
 9972                    if workspace.active_modal::<TestModal>(cx).is_some() {
 9973                        workspace.toggle_modal(window, cx, TestModal::new);
 9974                        workspace.toggle_modal(window, cx, TestModal::new);
 9975                    } else {
 9976                        workspace.toggle_modal(window, cx, TestModal::new);
 9977                    }
 9978                })
 9979            }
 9980        };
 9981
 9982        // If focus is transferred to another view that's not a panel or another pane, we still show
 9983        // the panel as zoomed.
 9984        focus_other_view(cx);
 9985        workspace.read_with(cx, |workspace, _| {
 9986            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9987            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9988        });
 9989
 9990        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9991        workspace.update_in(cx, |_workspace, window, cx| {
 9992            cx.focus_self(window);
 9993        });
 9994        workspace.read_with(cx, |workspace, _| {
 9995            assert_eq!(workspace.zoomed, None);
 9996            assert_eq!(workspace.zoomed_position, None);
 9997        });
 9998
 9999        // If focus is transferred again to another view that's not a panel or a pane, we won't
10000        // show the panel as zoomed because it wasn't zoomed before.
10001        focus_other_view(cx);
10002        workspace.read_with(cx, |workspace, _| {
10003            assert_eq!(workspace.zoomed, None);
10004            assert_eq!(workspace.zoomed_position, None);
10005        });
10006
10007        // When the panel is activated, it is zoomed again.
10008        cx.dispatch_action(ToggleRightDock);
10009        workspace.read_with(cx, |workspace, _| {
10010            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10011            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10012        });
10013
10014        // Emitting a ZoomOut event unzooms the panel.
10015        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10016        workspace.read_with(cx, |workspace, _| {
10017            assert_eq!(workspace.zoomed, None);
10018            assert_eq!(workspace.zoomed_position, None);
10019        });
10020
10021        // Emit closed event on panel 1, which is active
10022        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10023
10024        // Now the left dock is closed, because panel_1 was the active panel
10025        workspace.update(cx, |workspace, cx| {
10026            let right_dock = workspace.right_dock();
10027            assert!(!right_dock.read(cx).is_open());
10028        });
10029    }
10030
10031    #[gpui::test]
10032    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10033        init_test(cx);
10034
10035        let fs = FakeFs::new(cx.background_executor.clone());
10036        let project = Project::test(fs, [], cx).await;
10037        let (workspace, cx) =
10038            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10039        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10040
10041        let dirty_regular_buffer = cx.new(|cx| {
10042            TestItem::new(cx)
10043                .with_dirty(true)
10044                .with_label("1.txt")
10045                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10046        });
10047        let dirty_regular_buffer_2 = cx.new(|cx| {
10048            TestItem::new(cx)
10049                .with_dirty(true)
10050                .with_label("2.txt")
10051                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10052        });
10053        let dirty_multi_buffer_with_both = cx.new(|cx| {
10054            TestItem::new(cx)
10055                .with_dirty(true)
10056                .with_buffer_kind(ItemBufferKind::Multibuffer)
10057                .with_label("Fake Project Search")
10058                .with_project_items(&[
10059                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10060                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10061                ])
10062        });
10063        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10064        workspace.update_in(cx, |workspace, window, cx| {
10065            workspace.add_item(
10066                pane.clone(),
10067                Box::new(dirty_regular_buffer.clone()),
10068                None,
10069                false,
10070                false,
10071                window,
10072                cx,
10073            );
10074            workspace.add_item(
10075                pane.clone(),
10076                Box::new(dirty_regular_buffer_2.clone()),
10077                None,
10078                false,
10079                false,
10080                window,
10081                cx,
10082            );
10083            workspace.add_item(
10084                pane.clone(),
10085                Box::new(dirty_multi_buffer_with_both.clone()),
10086                None,
10087                false,
10088                false,
10089                window,
10090                cx,
10091            );
10092        });
10093
10094        pane.update_in(cx, |pane, window, cx| {
10095            pane.activate_item(2, true, true, window, cx);
10096            assert_eq!(
10097                pane.active_item().unwrap().item_id(),
10098                multi_buffer_with_both_files_id,
10099                "Should select the multi buffer in the pane"
10100            );
10101        });
10102        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10103            pane.close_other_items(
10104                &CloseOtherItems {
10105                    save_intent: Some(SaveIntent::Save),
10106                    close_pinned: true,
10107                },
10108                None,
10109                window,
10110                cx,
10111            )
10112        });
10113        cx.background_executor.run_until_parked();
10114        assert!(!cx.has_pending_prompt());
10115        close_all_but_multi_buffer_task
10116            .await
10117            .expect("Closing all buffers but the multi buffer failed");
10118        pane.update(cx, |pane, cx| {
10119            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10120            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10121            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10122            assert_eq!(pane.items_len(), 1);
10123            assert_eq!(
10124                pane.active_item().unwrap().item_id(),
10125                multi_buffer_with_both_files_id,
10126                "Should have only the multi buffer left in the pane"
10127            );
10128            assert!(
10129                dirty_multi_buffer_with_both.read(cx).is_dirty,
10130                "The multi buffer containing the unsaved buffer should still be dirty"
10131            );
10132        });
10133
10134        dirty_regular_buffer.update(cx, |buffer, cx| {
10135            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10136        });
10137
10138        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10139            pane.close_active_item(
10140                &CloseActiveItem {
10141                    save_intent: Some(SaveIntent::Close),
10142                    close_pinned: false,
10143                },
10144                window,
10145                cx,
10146            )
10147        });
10148        cx.background_executor.run_until_parked();
10149        assert!(
10150            cx.has_pending_prompt(),
10151            "Dirty multi buffer should prompt a save dialog"
10152        );
10153        cx.simulate_prompt_answer("Save");
10154        cx.background_executor.run_until_parked();
10155        close_multi_buffer_task
10156            .await
10157            .expect("Closing the multi buffer failed");
10158        pane.update(cx, |pane, cx| {
10159            assert_eq!(
10160                dirty_multi_buffer_with_both.read(cx).save_count,
10161                1,
10162                "Multi buffer item should get be saved"
10163            );
10164            // Test impl does not save inner items, so we do not assert them
10165            assert_eq!(
10166                pane.items_len(),
10167                0,
10168                "No more items should be left in the pane"
10169            );
10170            assert!(pane.active_item().is_none());
10171        });
10172    }
10173
10174    #[gpui::test]
10175    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10176        cx: &mut TestAppContext,
10177    ) {
10178        init_test(cx);
10179
10180        let fs = FakeFs::new(cx.background_executor.clone());
10181        let project = Project::test(fs, [], cx).await;
10182        let (workspace, cx) =
10183            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10184        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10185
10186        let dirty_regular_buffer = cx.new(|cx| {
10187            TestItem::new(cx)
10188                .with_dirty(true)
10189                .with_label("1.txt")
10190                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10191        });
10192        let dirty_regular_buffer_2 = cx.new(|cx| {
10193            TestItem::new(cx)
10194                .with_dirty(true)
10195                .with_label("2.txt")
10196                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10197        });
10198        let clear_regular_buffer = cx.new(|cx| {
10199            TestItem::new(cx)
10200                .with_label("3.txt")
10201                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10202        });
10203
10204        let dirty_multi_buffer_with_both = cx.new(|cx| {
10205            TestItem::new(cx)
10206                .with_dirty(true)
10207                .with_buffer_kind(ItemBufferKind::Multibuffer)
10208                .with_label("Fake Project Search")
10209                .with_project_items(&[
10210                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10211                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10212                    clear_regular_buffer.read(cx).project_items[0].clone(),
10213                ])
10214        });
10215        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10216        workspace.update_in(cx, |workspace, window, cx| {
10217            workspace.add_item(
10218                pane.clone(),
10219                Box::new(dirty_regular_buffer.clone()),
10220                None,
10221                false,
10222                false,
10223                window,
10224                cx,
10225            );
10226            workspace.add_item(
10227                pane.clone(),
10228                Box::new(dirty_multi_buffer_with_both.clone()),
10229                None,
10230                false,
10231                false,
10232                window,
10233                cx,
10234            );
10235        });
10236
10237        pane.update_in(cx, |pane, window, cx| {
10238            pane.activate_item(1, true, true, window, cx);
10239            assert_eq!(
10240                pane.active_item().unwrap().item_id(),
10241                multi_buffer_with_both_files_id,
10242                "Should select the multi buffer in the pane"
10243            );
10244        });
10245        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10246            pane.close_active_item(
10247                &CloseActiveItem {
10248                    save_intent: None,
10249                    close_pinned: false,
10250                },
10251                window,
10252                cx,
10253            )
10254        });
10255        cx.background_executor.run_until_parked();
10256        assert!(
10257            cx.has_pending_prompt(),
10258            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10259        );
10260    }
10261
10262    /// Tests that when `close_on_file_delete` is enabled, files are automatically
10263    /// closed when they are deleted from disk.
10264    #[gpui::test]
10265    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10266        init_test(cx);
10267
10268        // Enable the close_on_disk_deletion setting
10269        cx.update_global(|store: &mut SettingsStore, cx| {
10270            store.update_user_settings(cx, |settings| {
10271                settings.workspace.close_on_file_delete = Some(true);
10272            });
10273        });
10274
10275        let fs = FakeFs::new(cx.background_executor.clone());
10276        let project = Project::test(fs, [], cx).await;
10277        let (workspace, cx) =
10278            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10279        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10280
10281        // Create a test item that simulates a file
10282        let item = cx.new(|cx| {
10283            TestItem::new(cx)
10284                .with_label("test.txt")
10285                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10286        });
10287
10288        // Add item to workspace
10289        workspace.update_in(cx, |workspace, window, cx| {
10290            workspace.add_item(
10291                pane.clone(),
10292                Box::new(item.clone()),
10293                None,
10294                false,
10295                false,
10296                window,
10297                cx,
10298            );
10299        });
10300
10301        // Verify the item is in the pane
10302        pane.read_with(cx, |pane, _| {
10303            assert_eq!(pane.items().count(), 1);
10304        });
10305
10306        // Simulate file deletion by setting the item's deleted state
10307        item.update(cx, |item, _| {
10308            item.set_has_deleted_file(true);
10309        });
10310
10311        // Emit UpdateTab event to trigger the close behavior
10312        cx.run_until_parked();
10313        item.update(cx, |_, cx| {
10314            cx.emit(ItemEvent::UpdateTab);
10315        });
10316
10317        // Allow the close operation to complete
10318        cx.run_until_parked();
10319
10320        // Verify the item was automatically closed
10321        pane.read_with(cx, |pane, _| {
10322            assert_eq!(
10323                pane.items().count(),
10324                0,
10325                "Item should be automatically closed when file is deleted"
10326            );
10327        });
10328    }
10329
10330    /// Tests that when `close_on_file_delete` is disabled (default), files remain
10331    /// open with a strikethrough when they are deleted from disk.
10332    #[gpui::test]
10333    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10334        init_test(cx);
10335
10336        // Ensure close_on_disk_deletion is disabled (default)
10337        cx.update_global(|store: &mut SettingsStore, cx| {
10338            store.update_user_settings(cx, |settings| {
10339                settings.workspace.close_on_file_delete = Some(false);
10340            });
10341        });
10342
10343        let fs = FakeFs::new(cx.background_executor.clone());
10344        let project = Project::test(fs, [], cx).await;
10345        let (workspace, cx) =
10346            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10347        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10348
10349        // Create a test item that simulates a file
10350        let item = cx.new(|cx| {
10351            TestItem::new(cx)
10352                .with_label("test.txt")
10353                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10354        });
10355
10356        // Add item to workspace
10357        workspace.update_in(cx, |workspace, window, cx| {
10358            workspace.add_item(
10359                pane.clone(),
10360                Box::new(item.clone()),
10361                None,
10362                false,
10363                false,
10364                window,
10365                cx,
10366            );
10367        });
10368
10369        // Verify the item is in the pane
10370        pane.read_with(cx, |pane, _| {
10371            assert_eq!(pane.items().count(), 1);
10372        });
10373
10374        // Simulate file deletion
10375        item.update(cx, |item, _| {
10376            item.set_has_deleted_file(true);
10377        });
10378
10379        // Emit UpdateTab event
10380        cx.run_until_parked();
10381        item.update(cx, |_, cx| {
10382            cx.emit(ItemEvent::UpdateTab);
10383        });
10384
10385        // Allow any potential close operation to complete
10386        cx.run_until_parked();
10387
10388        // Verify the item remains open (with strikethrough)
10389        pane.read_with(cx, |pane, _| {
10390            assert_eq!(
10391                pane.items().count(),
10392                1,
10393                "Item should remain open when close_on_disk_deletion is disabled"
10394            );
10395        });
10396
10397        // Verify the item shows as deleted
10398        item.read_with(cx, |item, _| {
10399            assert!(
10400                item.has_deleted_file,
10401                "Item should be marked as having deleted file"
10402            );
10403        });
10404    }
10405
10406    /// Tests that dirty files are not automatically closed when deleted from disk,
10407    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10408    /// unsaved changes without being prompted.
10409    #[gpui::test]
10410    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10411        init_test(cx);
10412
10413        // Enable the close_on_file_delete setting
10414        cx.update_global(|store: &mut SettingsStore, cx| {
10415            store.update_user_settings(cx, |settings| {
10416                settings.workspace.close_on_file_delete = Some(true);
10417            });
10418        });
10419
10420        let fs = FakeFs::new(cx.background_executor.clone());
10421        let project = Project::test(fs, [], cx).await;
10422        let (workspace, cx) =
10423            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10424        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10425
10426        // Create a dirty test item
10427        let item = cx.new(|cx| {
10428            TestItem::new(cx)
10429                .with_dirty(true)
10430                .with_label("test.txt")
10431                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10432        });
10433
10434        // Add item to workspace
10435        workspace.update_in(cx, |workspace, window, cx| {
10436            workspace.add_item(
10437                pane.clone(),
10438                Box::new(item.clone()),
10439                None,
10440                false,
10441                false,
10442                window,
10443                cx,
10444            );
10445        });
10446
10447        // Simulate file deletion
10448        item.update(cx, |item, _| {
10449            item.set_has_deleted_file(true);
10450        });
10451
10452        // Emit UpdateTab event to trigger the close behavior
10453        cx.run_until_parked();
10454        item.update(cx, |_, cx| {
10455            cx.emit(ItemEvent::UpdateTab);
10456        });
10457
10458        // Allow any potential close operation to complete
10459        cx.run_until_parked();
10460
10461        // Verify the item remains open (dirty files are not auto-closed)
10462        pane.read_with(cx, |pane, _| {
10463            assert_eq!(
10464                pane.items().count(),
10465                1,
10466                "Dirty items should not be automatically closed even when file is deleted"
10467            );
10468        });
10469
10470        // Verify the item is marked as deleted and still dirty
10471        item.read_with(cx, |item, _| {
10472            assert!(
10473                item.has_deleted_file,
10474                "Item should be marked as having deleted file"
10475            );
10476            assert!(item.is_dirty, "Item should still be dirty");
10477        });
10478    }
10479
10480    /// Tests that navigation history is cleaned up when files are auto-closed
10481    /// due to deletion from disk.
10482    #[gpui::test]
10483    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10484        init_test(cx);
10485
10486        // Enable the close_on_file_delete setting
10487        cx.update_global(|store: &mut SettingsStore, cx| {
10488            store.update_user_settings(cx, |settings| {
10489                settings.workspace.close_on_file_delete = Some(true);
10490            });
10491        });
10492
10493        let fs = FakeFs::new(cx.background_executor.clone());
10494        let project = Project::test(fs, [], cx).await;
10495        let (workspace, cx) =
10496            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10497        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10498
10499        // Create test items
10500        let item1 = cx.new(|cx| {
10501            TestItem::new(cx)
10502                .with_label("test1.txt")
10503                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10504        });
10505        let item1_id = item1.item_id();
10506
10507        let item2 = cx.new(|cx| {
10508            TestItem::new(cx)
10509                .with_label("test2.txt")
10510                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10511        });
10512
10513        // Add items to workspace
10514        workspace.update_in(cx, |workspace, window, cx| {
10515            workspace.add_item(
10516                pane.clone(),
10517                Box::new(item1.clone()),
10518                None,
10519                false,
10520                false,
10521                window,
10522                cx,
10523            );
10524            workspace.add_item(
10525                pane.clone(),
10526                Box::new(item2.clone()),
10527                None,
10528                false,
10529                false,
10530                window,
10531                cx,
10532            );
10533        });
10534
10535        // Activate item1 to ensure it gets navigation entries
10536        pane.update_in(cx, |pane, window, cx| {
10537            pane.activate_item(0, true, true, window, cx);
10538        });
10539
10540        // Switch to item2 and back to create navigation history
10541        pane.update_in(cx, |pane, window, cx| {
10542            pane.activate_item(1, true, true, window, cx);
10543        });
10544        cx.run_until_parked();
10545
10546        pane.update_in(cx, |pane, window, cx| {
10547            pane.activate_item(0, true, true, window, cx);
10548        });
10549        cx.run_until_parked();
10550
10551        // Simulate file deletion for item1
10552        item1.update(cx, |item, _| {
10553            item.set_has_deleted_file(true);
10554        });
10555
10556        // Emit UpdateTab event to trigger the close behavior
10557        item1.update(cx, |_, cx| {
10558            cx.emit(ItemEvent::UpdateTab);
10559        });
10560        cx.run_until_parked();
10561
10562        // Verify item1 was closed
10563        pane.read_with(cx, |pane, _| {
10564            assert_eq!(
10565                pane.items().count(),
10566                1,
10567                "Should have 1 item remaining after auto-close"
10568            );
10569        });
10570
10571        // Check navigation history after close
10572        let has_item = pane.read_with(cx, |pane, cx| {
10573            let mut has_item = false;
10574            pane.nav_history().for_each_entry(cx, |entry, _| {
10575                if entry.item.id() == item1_id {
10576                    has_item = true;
10577                }
10578            });
10579            has_item
10580        });
10581
10582        assert!(
10583            !has_item,
10584            "Navigation history should not contain closed item entries"
10585        );
10586    }
10587
10588    #[gpui::test]
10589    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10590        cx: &mut TestAppContext,
10591    ) {
10592        init_test(cx);
10593
10594        let fs = FakeFs::new(cx.background_executor.clone());
10595        let project = Project::test(fs, [], cx).await;
10596        let (workspace, cx) =
10597            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10598        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10599
10600        let dirty_regular_buffer = cx.new(|cx| {
10601            TestItem::new(cx)
10602                .with_dirty(true)
10603                .with_label("1.txt")
10604                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10605        });
10606        let dirty_regular_buffer_2 = cx.new(|cx| {
10607            TestItem::new(cx)
10608                .with_dirty(true)
10609                .with_label("2.txt")
10610                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10611        });
10612        let clear_regular_buffer = cx.new(|cx| {
10613            TestItem::new(cx)
10614                .with_label("3.txt")
10615                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10616        });
10617
10618        let dirty_multi_buffer = cx.new(|cx| {
10619            TestItem::new(cx)
10620                .with_dirty(true)
10621                .with_buffer_kind(ItemBufferKind::Multibuffer)
10622                .with_label("Fake Project Search")
10623                .with_project_items(&[
10624                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10625                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10626                    clear_regular_buffer.read(cx).project_items[0].clone(),
10627                ])
10628        });
10629        workspace.update_in(cx, |workspace, window, cx| {
10630            workspace.add_item(
10631                pane.clone(),
10632                Box::new(dirty_regular_buffer.clone()),
10633                None,
10634                false,
10635                false,
10636                window,
10637                cx,
10638            );
10639            workspace.add_item(
10640                pane.clone(),
10641                Box::new(dirty_regular_buffer_2.clone()),
10642                None,
10643                false,
10644                false,
10645                window,
10646                cx,
10647            );
10648            workspace.add_item(
10649                pane.clone(),
10650                Box::new(dirty_multi_buffer.clone()),
10651                None,
10652                false,
10653                false,
10654                window,
10655                cx,
10656            );
10657        });
10658
10659        pane.update_in(cx, |pane, window, cx| {
10660            pane.activate_item(2, true, true, window, cx);
10661            assert_eq!(
10662                pane.active_item().unwrap().item_id(),
10663                dirty_multi_buffer.item_id(),
10664                "Should select the multi buffer in the pane"
10665            );
10666        });
10667        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10668            pane.close_active_item(
10669                &CloseActiveItem {
10670                    save_intent: None,
10671                    close_pinned: false,
10672                },
10673                window,
10674                cx,
10675            )
10676        });
10677        cx.background_executor.run_until_parked();
10678        assert!(
10679            !cx.has_pending_prompt(),
10680            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10681        );
10682        close_multi_buffer_task
10683            .await
10684            .expect("Closing multi buffer failed");
10685        pane.update(cx, |pane, cx| {
10686            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10687            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10688            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10689            assert_eq!(
10690                pane.items()
10691                    .map(|item| item.item_id())
10692                    .sorted()
10693                    .collect::<Vec<_>>(),
10694                vec![
10695                    dirty_regular_buffer.item_id(),
10696                    dirty_regular_buffer_2.item_id(),
10697                ],
10698                "Should have no multi buffer left in the pane"
10699            );
10700            assert!(dirty_regular_buffer.read(cx).is_dirty);
10701            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10702        });
10703    }
10704
10705    #[gpui::test]
10706    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10707        init_test(cx);
10708        let fs = FakeFs::new(cx.executor());
10709        let project = Project::test(fs, [], cx).await;
10710        let (workspace, cx) =
10711            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10712
10713        // Add a new panel to the right dock, opening the dock and setting the
10714        // focus to the new panel.
10715        let panel = workspace.update_in(cx, |workspace, window, cx| {
10716            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10717            workspace.add_panel(panel.clone(), window, cx);
10718
10719            workspace
10720                .right_dock()
10721                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10722
10723            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10724
10725            panel
10726        });
10727
10728        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10729        // panel to the next valid position which, in this case, is the left
10730        // dock.
10731        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10732        workspace.update(cx, |workspace, cx| {
10733            assert!(workspace.left_dock().read(cx).is_open());
10734            assert_eq!(panel.read(cx).position, DockPosition::Left);
10735        });
10736
10737        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10738        // panel to the next valid position which, in this case, is the bottom
10739        // dock.
10740        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10741        workspace.update(cx, |workspace, cx| {
10742            assert!(workspace.bottom_dock().read(cx).is_open());
10743            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10744        });
10745
10746        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10747        // around moving the panel to its initial position, the right dock.
10748        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10749        workspace.update(cx, |workspace, cx| {
10750            assert!(workspace.right_dock().read(cx).is_open());
10751            assert_eq!(panel.read(cx).position, DockPosition::Right);
10752        });
10753
10754        // Remove focus from the panel, ensuring that, if the panel is not
10755        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10756        // the panel's position, so the panel is still in the right dock.
10757        workspace.update_in(cx, |workspace, window, cx| {
10758            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10759        });
10760
10761        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10762        workspace.update(cx, |workspace, cx| {
10763            assert!(workspace.right_dock().read(cx).is_open());
10764            assert_eq!(panel.read(cx).position, DockPosition::Right);
10765        });
10766    }
10767
10768    #[gpui::test]
10769    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10770        init_test(cx);
10771
10772        let fs = FakeFs::new(cx.executor());
10773        let project = Project::test(fs, [], cx).await;
10774        let (workspace, cx) =
10775            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10776
10777        let item_1 = cx.new(|cx| {
10778            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10779        });
10780        workspace.update_in(cx, |workspace, window, cx| {
10781            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10782            workspace.move_item_to_pane_in_direction(
10783                &MoveItemToPaneInDirection {
10784                    direction: SplitDirection::Right,
10785                    focus: true,
10786                    clone: false,
10787                },
10788                window,
10789                cx,
10790            );
10791            workspace.move_item_to_pane_at_index(
10792                &MoveItemToPane {
10793                    destination: 3,
10794                    focus: true,
10795                    clone: false,
10796                },
10797                window,
10798                cx,
10799            );
10800
10801            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10802            assert_eq!(
10803                pane_items_paths(&workspace.active_pane, cx),
10804                vec!["first.txt".to_string()],
10805                "Single item was not moved anywhere"
10806            );
10807        });
10808
10809        let item_2 = cx.new(|cx| {
10810            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10811        });
10812        workspace.update_in(cx, |workspace, window, cx| {
10813            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10814            assert_eq!(
10815                pane_items_paths(&workspace.panes[0], cx),
10816                vec!["first.txt".to_string(), "second.txt".to_string()],
10817            );
10818            workspace.move_item_to_pane_in_direction(
10819                &MoveItemToPaneInDirection {
10820                    direction: SplitDirection::Right,
10821                    focus: true,
10822                    clone: false,
10823                },
10824                window,
10825                cx,
10826            );
10827
10828            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10829            assert_eq!(
10830                pane_items_paths(&workspace.panes[0], cx),
10831                vec!["first.txt".to_string()],
10832                "After moving, one item should be left in the original pane"
10833            );
10834            assert_eq!(
10835                pane_items_paths(&workspace.panes[1], cx),
10836                vec!["second.txt".to_string()],
10837                "New item should have been moved to the new pane"
10838            );
10839        });
10840
10841        let item_3 = cx.new(|cx| {
10842            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10843        });
10844        workspace.update_in(cx, |workspace, window, cx| {
10845            let original_pane = workspace.panes[0].clone();
10846            workspace.set_active_pane(&original_pane, window, cx);
10847            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10848            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10849            assert_eq!(
10850                pane_items_paths(&workspace.active_pane, cx),
10851                vec!["first.txt".to_string(), "third.txt".to_string()],
10852                "New pane should be ready to move one item out"
10853            );
10854
10855            workspace.move_item_to_pane_at_index(
10856                &MoveItemToPane {
10857                    destination: 3,
10858                    focus: true,
10859                    clone: false,
10860                },
10861                window,
10862                cx,
10863            );
10864            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10865            assert_eq!(
10866                pane_items_paths(&workspace.active_pane, cx),
10867                vec!["first.txt".to_string()],
10868                "After moving, one item should be left in the original pane"
10869            );
10870            assert_eq!(
10871                pane_items_paths(&workspace.panes[1], cx),
10872                vec!["second.txt".to_string()],
10873                "Previously created pane should be unchanged"
10874            );
10875            assert_eq!(
10876                pane_items_paths(&workspace.panes[2], cx),
10877                vec!["third.txt".to_string()],
10878                "New item should have been moved to the new pane"
10879            );
10880        });
10881    }
10882
10883    #[gpui::test]
10884    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10885        init_test(cx);
10886
10887        let fs = FakeFs::new(cx.executor());
10888        let project = Project::test(fs, [], cx).await;
10889        let (workspace, cx) =
10890            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10891
10892        let item_1 = cx.new(|cx| {
10893            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10894        });
10895        workspace.update_in(cx, |workspace, window, cx| {
10896            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10897            workspace.move_item_to_pane_in_direction(
10898                &MoveItemToPaneInDirection {
10899                    direction: SplitDirection::Right,
10900                    focus: true,
10901                    clone: true,
10902                },
10903                window,
10904                cx,
10905            );
10906            workspace.move_item_to_pane_at_index(
10907                &MoveItemToPane {
10908                    destination: 3,
10909                    focus: true,
10910                    clone: true,
10911                },
10912                window,
10913                cx,
10914            );
10915        });
10916        cx.run_until_parked();
10917
10918        workspace.update(cx, |workspace, cx| {
10919            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10920            for pane in workspace.panes() {
10921                assert_eq!(
10922                    pane_items_paths(pane, cx),
10923                    vec!["first.txt".to_string()],
10924                    "Single item exists in all panes"
10925                );
10926            }
10927        });
10928
10929        // verify that the active pane has been updated after waiting for the
10930        // pane focus event to fire and resolve
10931        workspace.read_with(cx, |workspace, _app| {
10932            assert_eq!(
10933                workspace.active_pane(),
10934                &workspace.panes[2],
10935                "The third pane should be the active one: {:?}",
10936                workspace.panes
10937            );
10938        })
10939    }
10940
10941    mod register_project_item_tests {
10942
10943        use super::*;
10944
10945        // View
10946        struct TestPngItemView {
10947            focus_handle: FocusHandle,
10948        }
10949        // Model
10950        struct TestPngItem {}
10951
10952        impl project::ProjectItem for TestPngItem {
10953            fn try_open(
10954                _project: &Entity<Project>,
10955                path: &ProjectPath,
10956                cx: &mut App,
10957            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10958                if path.path.extension().unwrap() == "png" {
10959                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10960                } else {
10961                    None
10962                }
10963            }
10964
10965            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10966                None
10967            }
10968
10969            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10970                None
10971            }
10972
10973            fn is_dirty(&self) -> bool {
10974                false
10975            }
10976        }
10977
10978        impl Item for TestPngItemView {
10979            type Event = ();
10980            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10981                "".into()
10982            }
10983        }
10984        impl EventEmitter<()> for TestPngItemView {}
10985        impl Focusable for TestPngItemView {
10986            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10987                self.focus_handle.clone()
10988            }
10989        }
10990
10991        impl Render for TestPngItemView {
10992            fn render(
10993                &mut self,
10994                _window: &mut Window,
10995                _cx: &mut Context<Self>,
10996            ) -> impl IntoElement {
10997                Empty
10998            }
10999        }
11000
11001        impl ProjectItem for TestPngItemView {
11002            type Item = TestPngItem;
11003
11004            fn for_project_item(
11005                _project: Entity<Project>,
11006                _pane: Option<&Pane>,
11007                _item: Entity<Self::Item>,
11008                _: &mut Window,
11009                cx: &mut Context<Self>,
11010            ) -> Self
11011            where
11012                Self: Sized,
11013            {
11014                Self {
11015                    focus_handle: cx.focus_handle(),
11016                }
11017            }
11018        }
11019
11020        // View
11021        struct TestIpynbItemView {
11022            focus_handle: FocusHandle,
11023        }
11024        // Model
11025        struct TestIpynbItem {}
11026
11027        impl project::ProjectItem for TestIpynbItem {
11028            fn try_open(
11029                _project: &Entity<Project>,
11030                path: &ProjectPath,
11031                cx: &mut App,
11032            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11033                if path.path.extension().unwrap() == "ipynb" {
11034                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11035                } else {
11036                    None
11037                }
11038            }
11039
11040            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11041                None
11042            }
11043
11044            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11045                None
11046            }
11047
11048            fn is_dirty(&self) -> bool {
11049                false
11050            }
11051        }
11052
11053        impl Item for TestIpynbItemView {
11054            type Event = ();
11055            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11056                "".into()
11057            }
11058        }
11059        impl EventEmitter<()> for TestIpynbItemView {}
11060        impl Focusable for TestIpynbItemView {
11061            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11062                self.focus_handle.clone()
11063            }
11064        }
11065
11066        impl Render for TestIpynbItemView {
11067            fn render(
11068                &mut self,
11069                _window: &mut Window,
11070                _cx: &mut Context<Self>,
11071            ) -> impl IntoElement {
11072                Empty
11073            }
11074        }
11075
11076        impl ProjectItem for TestIpynbItemView {
11077            type Item = TestIpynbItem;
11078
11079            fn for_project_item(
11080                _project: Entity<Project>,
11081                _pane: Option<&Pane>,
11082                _item: Entity<Self::Item>,
11083                _: &mut Window,
11084                cx: &mut Context<Self>,
11085            ) -> Self
11086            where
11087                Self: Sized,
11088            {
11089                Self {
11090                    focus_handle: cx.focus_handle(),
11091                }
11092            }
11093        }
11094
11095        struct TestAlternatePngItemView {
11096            focus_handle: FocusHandle,
11097        }
11098
11099        impl Item for TestAlternatePngItemView {
11100            type Event = ();
11101            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11102                "".into()
11103            }
11104        }
11105
11106        impl EventEmitter<()> for TestAlternatePngItemView {}
11107        impl Focusable for TestAlternatePngItemView {
11108            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11109                self.focus_handle.clone()
11110            }
11111        }
11112
11113        impl Render for TestAlternatePngItemView {
11114            fn render(
11115                &mut self,
11116                _window: &mut Window,
11117                _cx: &mut Context<Self>,
11118            ) -> impl IntoElement {
11119                Empty
11120            }
11121        }
11122
11123        impl ProjectItem for TestAlternatePngItemView {
11124            type Item = TestPngItem;
11125
11126            fn for_project_item(
11127                _project: Entity<Project>,
11128                _pane: Option<&Pane>,
11129                _item: Entity<Self::Item>,
11130                _: &mut Window,
11131                cx: &mut Context<Self>,
11132            ) -> Self
11133            where
11134                Self: Sized,
11135            {
11136                Self {
11137                    focus_handle: cx.focus_handle(),
11138                }
11139            }
11140        }
11141
11142        #[gpui::test]
11143        async fn test_register_project_item(cx: &mut TestAppContext) {
11144            init_test(cx);
11145
11146            cx.update(|cx| {
11147                register_project_item::<TestPngItemView>(cx);
11148                register_project_item::<TestIpynbItemView>(cx);
11149            });
11150
11151            let fs = FakeFs::new(cx.executor());
11152            fs.insert_tree(
11153                "/root1",
11154                json!({
11155                    "one.png": "BINARYDATAHERE",
11156                    "two.ipynb": "{ totally a notebook }",
11157                    "three.txt": "editing text, sure why not?"
11158                }),
11159            )
11160            .await;
11161
11162            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11163            let (workspace, cx) =
11164                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11165
11166            let worktree_id = project.update(cx, |project, cx| {
11167                project.worktrees(cx).next().unwrap().read(cx).id()
11168            });
11169
11170            let handle = workspace
11171                .update_in(cx, |workspace, window, cx| {
11172                    let project_path = (worktree_id, rel_path("one.png"));
11173                    workspace.open_path(project_path, None, true, window, cx)
11174                })
11175                .await
11176                .unwrap();
11177
11178            // Now we can check if the handle we got back errored or not
11179            assert_eq!(
11180                handle.to_any().entity_type(),
11181                TypeId::of::<TestPngItemView>()
11182            );
11183
11184            let handle = workspace
11185                .update_in(cx, |workspace, window, cx| {
11186                    let project_path = (worktree_id, rel_path("two.ipynb"));
11187                    workspace.open_path(project_path, None, true, window, cx)
11188                })
11189                .await
11190                .unwrap();
11191
11192            assert_eq!(
11193                handle.to_any().entity_type(),
11194                TypeId::of::<TestIpynbItemView>()
11195            );
11196
11197            let handle = workspace
11198                .update_in(cx, |workspace, window, cx| {
11199                    let project_path = (worktree_id, rel_path("three.txt"));
11200                    workspace.open_path(project_path, None, true, window, cx)
11201                })
11202                .await;
11203            assert!(handle.is_err());
11204        }
11205
11206        #[gpui::test]
11207        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11208            init_test(cx);
11209
11210            cx.update(|cx| {
11211                register_project_item::<TestPngItemView>(cx);
11212                register_project_item::<TestAlternatePngItemView>(cx);
11213            });
11214
11215            let fs = FakeFs::new(cx.executor());
11216            fs.insert_tree(
11217                "/root1",
11218                json!({
11219                    "one.png": "BINARYDATAHERE",
11220                    "two.ipynb": "{ totally a notebook }",
11221                    "three.txt": "editing text, sure why not?"
11222                }),
11223            )
11224            .await;
11225            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11226            let (workspace, cx) =
11227                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11228            let worktree_id = project.update(cx, |project, cx| {
11229                project.worktrees(cx).next().unwrap().read(cx).id()
11230            });
11231
11232            let handle = workspace
11233                .update_in(cx, |workspace, window, cx| {
11234                    let project_path = (worktree_id, rel_path("one.png"));
11235                    workspace.open_path(project_path, None, true, window, cx)
11236                })
11237                .await
11238                .unwrap();
11239
11240            // This _must_ be the second item registered
11241            assert_eq!(
11242                handle.to_any().entity_type(),
11243                TypeId::of::<TestAlternatePngItemView>()
11244            );
11245
11246            let handle = workspace
11247                .update_in(cx, |workspace, window, cx| {
11248                    let project_path = (worktree_id, rel_path("three.txt"));
11249                    workspace.open_path(project_path, None, true, window, cx)
11250                })
11251                .await;
11252            assert!(handle.is_err());
11253        }
11254    }
11255
11256    #[gpui::test]
11257    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11258        init_test(cx);
11259
11260        let fs = FakeFs::new(cx.executor());
11261        let project = Project::test(fs, [], cx).await;
11262        let (workspace, _cx) =
11263            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11264
11265        // Test with status bar shown (default)
11266        workspace.read_with(cx, |workspace, cx| {
11267            let visible = workspace.status_bar_visible(cx);
11268            assert!(visible, "Status bar should be visible by default");
11269        });
11270
11271        // Test with status bar hidden
11272        cx.update_global(|store: &mut SettingsStore, cx| {
11273            store.update_user_settings(cx, |settings| {
11274                settings.status_bar.get_or_insert_default().show = Some(false);
11275            });
11276        });
11277
11278        workspace.read_with(cx, |workspace, cx| {
11279            let visible = workspace.status_bar_visible(cx);
11280            assert!(!visible, "Status bar should be hidden when show is false");
11281        });
11282
11283        // Test with status bar shown explicitly
11284        cx.update_global(|store: &mut SettingsStore, cx| {
11285            store.update_user_settings(cx, |settings| {
11286                settings.status_bar.get_or_insert_default().show = Some(true);
11287            });
11288        });
11289
11290        workspace.read_with(cx, |workspace, cx| {
11291            let visible = workspace.status_bar_visible(cx);
11292            assert!(visible, "Status bar should be visible when show is true");
11293        });
11294    }
11295
11296    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11297        pane.read(cx)
11298            .items()
11299            .flat_map(|item| {
11300                item.project_paths(cx)
11301                    .into_iter()
11302                    .map(|path| path.path.display(PathStyle::local()).into_owned())
11303            })
11304            .collect()
11305    }
11306
11307    pub fn init_test(cx: &mut TestAppContext) {
11308        cx.update(|cx| {
11309            let settings_store = SettingsStore::test(cx);
11310            cx.set_global(settings_store);
11311            theme::init(theme::LoadThemes::JustBase, cx);
11312            language::init(cx);
11313            crate::init_settings(cx);
11314            Project::init_settings(cx);
11315        });
11316    }
11317
11318    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11319        let item = TestProjectItem::new(id, path, cx);
11320        item.update(cx, |item, _| {
11321            item.is_dirty = true;
11322        });
11323        item
11324    }
11325}