workspace.rs

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