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                .detach();
 3635        }
 3636    }
 3637
 3638    fn move_item_to_pane_at_index(
 3639        &mut self,
 3640        action: &MoveItemToPane,
 3641        window: &mut Window,
 3642        cx: &mut Context<Self>,
 3643    ) {
 3644        let panes = self.center.panes();
 3645        let destination = match panes.get(action.destination) {
 3646            Some(&destination) => destination.clone(),
 3647            None => {
 3648                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3649                    return;
 3650                }
 3651                let direction = SplitDirection::Right;
 3652                let split_off_pane = self
 3653                    .find_pane_in_direction(direction, cx)
 3654                    .unwrap_or_else(|| self.active_pane.clone());
 3655                let new_pane = self.add_pane(window, cx);
 3656                if self
 3657                    .center
 3658                    .split(&split_off_pane, &new_pane, direction)
 3659                    .log_err()
 3660                    .is_none()
 3661                {
 3662                    return;
 3663                };
 3664                new_pane
 3665            }
 3666        };
 3667
 3668        if action.clone {
 3669            clone_active_item(
 3670                self.database_id(),
 3671                &self.active_pane,
 3672                &destination,
 3673                action.focus,
 3674                window,
 3675                cx,
 3676            )
 3677        } else {
 3678            move_active_item(
 3679                &self.active_pane,
 3680                &destination,
 3681                action.focus,
 3682                true,
 3683                window,
 3684                cx,
 3685            )
 3686        }
 3687    }
 3688
 3689    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3690        let panes = self.center.panes();
 3691        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3692            let next_ix = (ix + 1) % panes.len();
 3693            let next_pane = panes[next_ix].clone();
 3694            window.focus(&next_pane.focus_handle(cx));
 3695        }
 3696    }
 3697
 3698    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3699        let panes = self.center.panes();
 3700        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3701            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3702            let prev_pane = panes[prev_ix].clone();
 3703            window.focus(&prev_pane.focus_handle(cx));
 3704        }
 3705    }
 3706
 3707    pub fn activate_pane_in_direction(
 3708        &mut self,
 3709        direction: SplitDirection,
 3710        window: &mut Window,
 3711        cx: &mut App,
 3712    ) {
 3713        use ActivateInDirectionTarget as Target;
 3714        enum Origin {
 3715            LeftDock,
 3716            RightDock,
 3717            BottomDock,
 3718            Center,
 3719        }
 3720
 3721        let origin: Origin = [
 3722            (&self.left_dock, Origin::LeftDock),
 3723            (&self.right_dock, Origin::RightDock),
 3724            (&self.bottom_dock, Origin::BottomDock),
 3725        ]
 3726        .into_iter()
 3727        .find_map(|(dock, origin)| {
 3728            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 3729                Some(origin)
 3730            } else {
 3731                None
 3732            }
 3733        })
 3734        .unwrap_or(Origin::Center);
 3735
 3736        let get_last_active_pane = || {
 3737            let pane = self
 3738                .last_active_center_pane
 3739                .clone()
 3740                .unwrap_or_else(|| {
 3741                    self.panes
 3742                        .first()
 3743                        .expect("There must be an active pane")
 3744                        .downgrade()
 3745                })
 3746                .upgrade()?;
 3747            (pane.read(cx).items_len() != 0).then_some(pane)
 3748        };
 3749
 3750        let try_dock =
 3751            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 3752
 3753        let target = match (origin, direction) {
 3754            // We're in the center, so we first try to go to a different pane,
 3755            // otherwise try to go to a dock.
 3756            (Origin::Center, direction) => {
 3757                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 3758                    Some(Target::Pane(pane))
 3759                } else {
 3760                    match direction {
 3761                        SplitDirection::Up => None,
 3762                        SplitDirection::Down => try_dock(&self.bottom_dock),
 3763                        SplitDirection::Left => try_dock(&self.left_dock),
 3764                        SplitDirection::Right => try_dock(&self.right_dock),
 3765                    }
 3766                }
 3767            }
 3768
 3769            (Origin::LeftDock, SplitDirection::Right) => {
 3770                if let Some(last_active_pane) = get_last_active_pane() {
 3771                    Some(Target::Pane(last_active_pane))
 3772                } else {
 3773                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 3774                }
 3775            }
 3776
 3777            (Origin::LeftDock, SplitDirection::Down)
 3778            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 3779
 3780            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 3781            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 3782            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 3783
 3784            (Origin::RightDock, SplitDirection::Left) => {
 3785                if let Some(last_active_pane) = get_last_active_pane() {
 3786                    Some(Target::Pane(last_active_pane))
 3787                } else {
 3788                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 3789                }
 3790            }
 3791
 3792            _ => None,
 3793        };
 3794
 3795        match target {
 3796            Some(ActivateInDirectionTarget::Pane(pane)) => {
 3797                let pane = pane.read(cx);
 3798                if let Some(item) = pane.active_item() {
 3799                    item.item_focus_handle(cx).focus(window);
 3800                } else {
 3801                    log::error!(
 3802                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 3803                    );
 3804                }
 3805            }
 3806            Some(ActivateInDirectionTarget::Dock(dock)) => {
 3807                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 3808                window.defer(cx, move |window, cx| {
 3809                    let dock = dock.read(cx);
 3810                    if let Some(panel) = dock.active_panel() {
 3811                        panel.panel_focus_handle(cx).focus(window);
 3812                    } else {
 3813                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 3814                    }
 3815                })
 3816            }
 3817            None => {}
 3818        }
 3819    }
 3820
 3821    pub fn move_item_to_pane_in_direction(
 3822        &mut self,
 3823        action: &MoveItemToPaneInDirection,
 3824        window: &mut Window,
 3825        cx: &mut Context<Self>,
 3826    ) {
 3827        let destination = match self.find_pane_in_direction(action.direction, cx) {
 3828            Some(destination) => destination,
 3829            None => {
 3830                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3831                    return;
 3832                }
 3833                let new_pane = self.add_pane(window, cx);
 3834                if self
 3835                    .center
 3836                    .split(&self.active_pane, &new_pane, action.direction)
 3837                    .log_err()
 3838                    .is_none()
 3839                {
 3840                    return;
 3841                };
 3842                new_pane
 3843            }
 3844        };
 3845
 3846        if action.clone {
 3847            clone_active_item(
 3848                self.database_id(),
 3849                &self.active_pane,
 3850                &destination,
 3851                action.focus,
 3852                window,
 3853                cx,
 3854            )
 3855        } else {
 3856            move_active_item(
 3857                &self.active_pane,
 3858                &destination,
 3859                action.focus,
 3860                true,
 3861                window,
 3862                cx,
 3863            );
 3864        }
 3865    }
 3866
 3867    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 3868        self.center.bounding_box_for_pane(pane)
 3869    }
 3870
 3871    pub fn find_pane_in_direction(
 3872        &mut self,
 3873        direction: SplitDirection,
 3874        cx: &App,
 3875    ) -> Option<Entity<Pane>> {
 3876        self.center
 3877            .find_pane_in_direction(&self.active_pane, direction, cx)
 3878            .cloned()
 3879    }
 3880
 3881    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 3882        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 3883            self.center.swap(&self.active_pane, &to);
 3884            cx.notify();
 3885        }
 3886    }
 3887
 3888    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 3889        if self
 3890            .center
 3891            .move_to_border(&self.active_pane, direction)
 3892            .unwrap()
 3893        {
 3894            cx.notify();
 3895        }
 3896    }
 3897
 3898    pub fn resize_pane(
 3899        &mut self,
 3900        axis: gpui::Axis,
 3901        amount: Pixels,
 3902        window: &mut Window,
 3903        cx: &mut Context<Self>,
 3904    ) {
 3905        let docks = self.all_docks();
 3906        let active_dock = docks
 3907            .into_iter()
 3908            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3909
 3910        if let Some(dock) = active_dock {
 3911            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 3912                return;
 3913            };
 3914            match dock.read(cx).position() {
 3915                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 3916                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 3917                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 3918            }
 3919        } else {
 3920            self.center
 3921                .resize(&self.active_pane, axis, amount, &self.bounds);
 3922        }
 3923        cx.notify();
 3924    }
 3925
 3926    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 3927        self.center.reset_pane_sizes();
 3928        cx.notify();
 3929    }
 3930
 3931    fn handle_pane_focused(
 3932        &mut self,
 3933        pane: Entity<Pane>,
 3934        window: &mut Window,
 3935        cx: &mut Context<Self>,
 3936    ) {
 3937        // This is explicitly hoisted out of the following check for pane identity as
 3938        // terminal panel panes are not registered as a center panes.
 3939        self.status_bar.update(cx, |status_bar, cx| {
 3940            status_bar.set_active_pane(&pane, window, cx);
 3941        });
 3942        if self.active_pane != pane {
 3943            self.set_active_pane(&pane, window, cx);
 3944        }
 3945
 3946        if self.last_active_center_pane.is_none() {
 3947            self.last_active_center_pane = Some(pane.downgrade());
 3948        }
 3949
 3950        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 3951        if pane.read(cx).is_zoomed() {
 3952            self.zoomed = Some(pane.downgrade().into());
 3953        } else {
 3954            self.zoomed = None;
 3955        }
 3956        self.zoomed_position = None;
 3957        cx.emit(Event::ZoomChanged);
 3958        self.update_active_view_for_followers(window, cx);
 3959        pane.update(cx, |pane, _| {
 3960            pane.track_alternate_file_items();
 3961        });
 3962
 3963        cx.notify();
 3964    }
 3965
 3966    fn set_active_pane(
 3967        &mut self,
 3968        pane: &Entity<Pane>,
 3969        window: &mut Window,
 3970        cx: &mut Context<Self>,
 3971    ) {
 3972        self.active_pane = pane.clone();
 3973        self.active_item_path_changed(window, cx);
 3974        self.last_active_center_pane = Some(pane.downgrade());
 3975    }
 3976
 3977    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3978        self.update_active_view_for_followers(window, cx);
 3979    }
 3980
 3981    fn handle_pane_event(
 3982        &mut self,
 3983        pane: &Entity<Pane>,
 3984        event: &pane::Event,
 3985        window: &mut Window,
 3986        cx: &mut Context<Self>,
 3987    ) {
 3988        let mut serialize_workspace = true;
 3989        match event {
 3990            pane::Event::AddItem { item } => {
 3991                item.added_to_pane(self, pane.clone(), window, cx);
 3992                cx.emit(Event::ItemAdded {
 3993                    item: item.boxed_clone(),
 3994                });
 3995            }
 3996            pane::Event::Split {
 3997                direction,
 3998                clone_active_item,
 3999            } => {
 4000                if *clone_active_item {
 4001                    self.split_and_clone(pane.clone(), *direction, window, cx)
 4002                        .detach();
 4003                } else {
 4004                    self.split_and_move(pane.clone(), *direction, window, cx);
 4005                }
 4006            }
 4007            pane::Event::JoinIntoNext => {
 4008                self.join_pane_into_next(pane.clone(), window, cx);
 4009            }
 4010            pane::Event::JoinAll => {
 4011                self.join_all_panes(window, cx);
 4012            }
 4013            pane::Event::Remove { focus_on_pane } => {
 4014                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4015            }
 4016            pane::Event::ActivateItem {
 4017                local,
 4018                focus_changed,
 4019            } => {
 4020                window.invalidate_character_coordinates();
 4021
 4022                pane.update(cx, |pane, _| {
 4023                    pane.track_alternate_file_items();
 4024                });
 4025                if *local {
 4026                    self.unfollow_in_pane(pane, window, cx);
 4027                }
 4028                serialize_workspace = *focus_changed || pane != self.active_pane();
 4029                if pane == self.active_pane() {
 4030                    self.active_item_path_changed(window, cx);
 4031                    self.update_active_view_for_followers(window, cx);
 4032                } else if *local {
 4033                    self.set_active_pane(pane, window, cx);
 4034                }
 4035            }
 4036            pane::Event::UserSavedItem { item, save_intent } => {
 4037                cx.emit(Event::UserSavedItem {
 4038                    pane: pane.downgrade(),
 4039                    item: item.boxed_clone(),
 4040                    save_intent: *save_intent,
 4041                });
 4042                serialize_workspace = false;
 4043            }
 4044            pane::Event::ChangeItemTitle => {
 4045                if *pane == self.active_pane {
 4046                    self.active_item_path_changed(window, cx);
 4047                }
 4048                serialize_workspace = false;
 4049            }
 4050            pane::Event::RemovedItem { item } => {
 4051                cx.emit(Event::ActiveItemChanged);
 4052                self.update_window_edited(window, cx);
 4053                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4054                    && entry.get().entity_id() == pane.entity_id()
 4055                {
 4056                    entry.remove();
 4057                }
 4058                cx.emit(Event::ItemRemoved {
 4059                    item_id: item.item_id(),
 4060                });
 4061            }
 4062            pane::Event::Focus => {
 4063                window.invalidate_character_coordinates();
 4064                self.handle_pane_focused(pane.clone(), window, cx);
 4065            }
 4066            pane::Event::ZoomIn => {
 4067                if *pane == self.active_pane {
 4068                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4069                    if pane.read(cx).has_focus(window, cx) {
 4070                        self.zoomed = Some(pane.downgrade().into());
 4071                        self.zoomed_position = None;
 4072                        cx.emit(Event::ZoomChanged);
 4073                    }
 4074                    cx.notify();
 4075                }
 4076            }
 4077            pane::Event::ZoomOut => {
 4078                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4079                if self.zoomed_position.is_none() {
 4080                    self.zoomed = None;
 4081                    cx.emit(Event::ZoomChanged);
 4082                }
 4083                cx.notify();
 4084            }
 4085            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4086        }
 4087
 4088        if serialize_workspace {
 4089            self.serialize_workspace(window, cx);
 4090        }
 4091    }
 4092
 4093    pub fn unfollow_in_pane(
 4094        &mut self,
 4095        pane: &Entity<Pane>,
 4096        window: &mut Window,
 4097        cx: &mut Context<Workspace>,
 4098    ) -> Option<CollaboratorId> {
 4099        let leader_id = self.leader_for_pane(pane)?;
 4100        self.unfollow(leader_id, window, cx);
 4101        Some(leader_id)
 4102    }
 4103
 4104    pub fn split_pane(
 4105        &mut self,
 4106        pane_to_split: Entity<Pane>,
 4107        split_direction: SplitDirection,
 4108        window: &mut Window,
 4109        cx: &mut Context<Self>,
 4110    ) -> Entity<Pane> {
 4111        let new_pane = self.add_pane(window, cx);
 4112        self.center
 4113            .split(&pane_to_split, &new_pane, split_direction)
 4114            .unwrap();
 4115        cx.notify();
 4116        new_pane
 4117    }
 4118
 4119    pub fn split_and_move(
 4120        &mut self,
 4121        pane: Entity<Pane>,
 4122        direction: SplitDirection,
 4123        window: &mut Window,
 4124        cx: &mut Context<Self>,
 4125    ) {
 4126        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4127            return;
 4128        };
 4129        let new_pane = self.add_pane(window, cx);
 4130        new_pane.update(cx, |pane, cx| {
 4131            pane.add_item(item, true, true, None, window, cx)
 4132        });
 4133        self.center.split(&pane, &new_pane, direction).unwrap();
 4134        cx.notify();
 4135    }
 4136
 4137    pub fn split_and_clone(
 4138        &mut self,
 4139        pane: Entity<Pane>,
 4140        direction: SplitDirection,
 4141        window: &mut Window,
 4142        cx: &mut Context<Self>,
 4143    ) -> Task<Option<Entity<Pane>>> {
 4144        let Some(item) = pane.read(cx).active_item() else {
 4145            return Task::ready(None);
 4146        };
 4147        let task = item.clone_on_split(self.database_id(), window, cx);
 4148        cx.spawn_in(window, async move |this, cx| {
 4149            if let Some(clone) = task.await {
 4150                this.update_in(cx, |this, window, cx| {
 4151                    let new_pane = this.add_pane(window, cx);
 4152                    new_pane.update(cx, |pane, cx| {
 4153                        pane.add_item(clone, true, true, None, window, cx)
 4154                    });
 4155                    this.center.split(&pane, &new_pane, direction).unwrap();
 4156                    cx.notify();
 4157                    new_pane
 4158                })
 4159                .ok()
 4160            } else {
 4161                None
 4162            }
 4163        })
 4164    }
 4165
 4166    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4167        let active_item = self.active_pane.read(cx).active_item();
 4168        for pane in &self.panes {
 4169            join_pane_into_active(&self.active_pane, pane, window, cx);
 4170        }
 4171        if let Some(active_item) = active_item {
 4172            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4173        }
 4174        cx.notify();
 4175    }
 4176
 4177    pub fn join_pane_into_next(
 4178        &mut self,
 4179        pane: Entity<Pane>,
 4180        window: &mut Window,
 4181        cx: &mut Context<Self>,
 4182    ) {
 4183        let next_pane = self
 4184            .find_pane_in_direction(SplitDirection::Right, cx)
 4185            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4186            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4187            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4188        let Some(next_pane) = next_pane else {
 4189            return;
 4190        };
 4191        move_all_items(&pane, &next_pane, window, cx);
 4192        cx.notify();
 4193    }
 4194
 4195    fn remove_pane(
 4196        &mut self,
 4197        pane: Entity<Pane>,
 4198        focus_on: Option<Entity<Pane>>,
 4199        window: &mut Window,
 4200        cx: &mut Context<Self>,
 4201    ) {
 4202        if self.center.remove(&pane).unwrap() {
 4203            self.force_remove_pane(&pane, &focus_on, window, cx);
 4204            self.unfollow_in_pane(&pane, window, cx);
 4205            self.last_leaders_by_pane.remove(&pane.downgrade());
 4206            for removed_item in pane.read(cx).items() {
 4207                self.panes_by_item.remove(&removed_item.item_id());
 4208            }
 4209
 4210            cx.notify();
 4211        } else {
 4212            self.active_item_path_changed(window, cx);
 4213        }
 4214        cx.emit(Event::PaneRemoved);
 4215    }
 4216
 4217    pub fn panes(&self) -> &[Entity<Pane>] {
 4218        &self.panes
 4219    }
 4220
 4221    pub fn active_pane(&self) -> &Entity<Pane> {
 4222        &self.active_pane
 4223    }
 4224
 4225    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4226        for dock in self.all_docks() {
 4227            if dock.focus_handle(cx).contains_focused(window, cx)
 4228                && let Some(pane) = dock
 4229                    .read(cx)
 4230                    .active_panel()
 4231                    .and_then(|panel| panel.pane(cx))
 4232            {
 4233                return pane;
 4234            }
 4235        }
 4236        self.active_pane().clone()
 4237    }
 4238
 4239    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4240        self.find_pane_in_direction(SplitDirection::Right, cx)
 4241            .unwrap_or_else(|| {
 4242                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4243            })
 4244    }
 4245
 4246    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4247        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4248        weak_pane.upgrade()
 4249    }
 4250
 4251    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4252        self.follower_states.retain(|leader_id, state| {
 4253            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4254                for item in state.items_by_leader_view_id.values() {
 4255                    item.view.set_leader_id(None, window, cx);
 4256                }
 4257                false
 4258            } else {
 4259                true
 4260            }
 4261        });
 4262        cx.notify();
 4263    }
 4264
 4265    pub fn start_following(
 4266        &mut self,
 4267        leader_id: impl Into<CollaboratorId>,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) -> Option<Task<Result<()>>> {
 4271        let leader_id = leader_id.into();
 4272        let pane = self.active_pane().clone();
 4273
 4274        self.last_leaders_by_pane
 4275            .insert(pane.downgrade(), leader_id);
 4276        self.unfollow(leader_id, window, cx);
 4277        self.unfollow_in_pane(&pane, window, cx);
 4278        self.follower_states.insert(
 4279            leader_id,
 4280            FollowerState {
 4281                center_pane: pane.clone(),
 4282                dock_pane: None,
 4283                active_view_id: None,
 4284                items_by_leader_view_id: Default::default(),
 4285            },
 4286        );
 4287        cx.notify();
 4288
 4289        match leader_id {
 4290            CollaboratorId::PeerId(leader_peer_id) => {
 4291                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4292                let project_id = self.project.read(cx).remote_id();
 4293                let request = self.app_state.client.request(proto::Follow {
 4294                    room_id,
 4295                    project_id,
 4296                    leader_id: Some(leader_peer_id),
 4297                });
 4298
 4299                Some(cx.spawn_in(window, async move |this, cx| {
 4300                    let response = request.await?;
 4301                    this.update(cx, |this, _| {
 4302                        let state = this
 4303                            .follower_states
 4304                            .get_mut(&leader_id)
 4305                            .context("following interrupted")?;
 4306                        state.active_view_id = response
 4307                            .active_view
 4308                            .as_ref()
 4309                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4310                        anyhow::Ok(())
 4311                    })??;
 4312                    if let Some(view) = response.active_view {
 4313                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4314                    }
 4315                    this.update_in(cx, |this, window, cx| {
 4316                        this.leader_updated(leader_id, window, cx)
 4317                    })?;
 4318                    Ok(())
 4319                }))
 4320            }
 4321            CollaboratorId::Agent => {
 4322                self.leader_updated(leader_id, window, cx)?;
 4323                Some(Task::ready(Ok(())))
 4324            }
 4325        }
 4326    }
 4327
 4328    pub fn follow_next_collaborator(
 4329        &mut self,
 4330        _: &FollowNextCollaborator,
 4331        window: &mut Window,
 4332        cx: &mut Context<Self>,
 4333    ) {
 4334        let collaborators = self.project.read(cx).collaborators();
 4335        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4336            let mut collaborators = collaborators.keys().copied();
 4337            for peer_id in collaborators.by_ref() {
 4338                if CollaboratorId::PeerId(peer_id) == leader_id {
 4339                    break;
 4340                }
 4341            }
 4342            collaborators.next().map(CollaboratorId::PeerId)
 4343        } else if let Some(last_leader_id) =
 4344            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4345        {
 4346            match last_leader_id {
 4347                CollaboratorId::PeerId(peer_id) => {
 4348                    if collaborators.contains_key(peer_id) {
 4349                        Some(*last_leader_id)
 4350                    } else {
 4351                        None
 4352                    }
 4353                }
 4354                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4355            }
 4356        } else {
 4357            None
 4358        };
 4359
 4360        let pane = self.active_pane.clone();
 4361        let Some(leader_id) = next_leader_id.or_else(|| {
 4362            Some(CollaboratorId::PeerId(
 4363                collaborators.keys().copied().next()?,
 4364            ))
 4365        }) else {
 4366            return;
 4367        };
 4368        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4369            return;
 4370        }
 4371        if let Some(task) = self.start_following(leader_id, window, cx) {
 4372            task.detach_and_log_err(cx)
 4373        }
 4374    }
 4375
 4376    pub fn follow(
 4377        &mut self,
 4378        leader_id: impl Into<CollaboratorId>,
 4379        window: &mut Window,
 4380        cx: &mut Context<Self>,
 4381    ) {
 4382        let leader_id = leader_id.into();
 4383
 4384        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4385            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4386                return;
 4387            };
 4388            let room = room.read(cx);
 4389            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4390                return;
 4391            };
 4392
 4393            let project = self.project.read(cx);
 4394
 4395            let other_project_id = match remote_participant.location {
 4396                call::ParticipantLocation::External => None,
 4397                call::ParticipantLocation::UnsharedProject => None,
 4398                call::ParticipantLocation::SharedProject { project_id } => {
 4399                    if Some(project_id) == project.remote_id() {
 4400                        None
 4401                    } else {
 4402                        Some(project_id)
 4403                    }
 4404                }
 4405            };
 4406
 4407            // if they are active in another project, follow there.
 4408            if let Some(project_id) = other_project_id {
 4409                let app_state = self.app_state.clone();
 4410                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4411                    .detach_and_log_err(cx);
 4412            }
 4413        }
 4414
 4415        // if you're already following, find the right pane and focus it.
 4416        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4417            window.focus(&follower_state.pane().focus_handle(cx));
 4418
 4419            return;
 4420        }
 4421
 4422        // Otherwise, follow.
 4423        if let Some(task) = self.start_following(leader_id, window, cx) {
 4424            task.detach_and_log_err(cx)
 4425        }
 4426    }
 4427
 4428    pub fn unfollow(
 4429        &mut self,
 4430        leader_id: impl Into<CollaboratorId>,
 4431        window: &mut Window,
 4432        cx: &mut Context<Self>,
 4433    ) -> Option<()> {
 4434        cx.notify();
 4435
 4436        let leader_id = leader_id.into();
 4437        let state = self.follower_states.remove(&leader_id)?;
 4438        for (_, item) in state.items_by_leader_view_id {
 4439            item.view.set_leader_id(None, window, cx);
 4440        }
 4441
 4442        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4443            let project_id = self.project.read(cx).remote_id();
 4444            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4445            self.app_state
 4446                .client
 4447                .send(proto::Unfollow {
 4448                    room_id,
 4449                    project_id,
 4450                    leader_id: Some(leader_peer_id),
 4451                })
 4452                .log_err();
 4453        }
 4454
 4455        Some(())
 4456    }
 4457
 4458    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4459        self.follower_states.contains_key(&id.into())
 4460    }
 4461
 4462    fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4463        cx.emit(Event::ActiveItemChanged);
 4464        let active_entry = self.active_project_path(cx);
 4465        self.project.update(cx, |project, cx| {
 4466            project.set_active_path(active_entry.clone(), cx)
 4467        });
 4468
 4469        if let Some(project_path) = &active_entry {
 4470            let git_store_entity = self.project.read(cx).git_store().clone();
 4471            git_store_entity.update(cx, |git_store, cx| {
 4472                git_store.set_active_repo_for_path(project_path, cx);
 4473            });
 4474        }
 4475
 4476        self.update_window_title(window, cx);
 4477    }
 4478
 4479    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4480        let project = self.project().read(cx);
 4481        let mut title = String::new();
 4482
 4483        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 4484            let name = {
 4485                let settings_location = SettingsLocation {
 4486                    worktree_id: worktree.read(cx).id(),
 4487                    path: RelPath::empty(),
 4488                };
 4489
 4490                let settings = WorktreeSettings::get(Some(settings_location), cx);
 4491                match &settings.project_name {
 4492                    Some(name) => name.as_str(),
 4493                    None => worktree.read(cx).root_name_str(),
 4494                }
 4495            };
 4496            if i > 0 {
 4497                title.push_str(", ");
 4498            }
 4499            title.push_str(name);
 4500        }
 4501
 4502        if title.is_empty() {
 4503            title = "empty project".to_string();
 4504        }
 4505
 4506        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4507            let filename = path.path.file_name().or_else(|| {
 4508                Some(
 4509                    project
 4510                        .worktree_for_id(path.worktree_id, cx)?
 4511                        .read(cx)
 4512                        .root_name_str(),
 4513                )
 4514            });
 4515
 4516            if let Some(filename) = filename {
 4517                title.push_str("");
 4518                title.push_str(filename.as_ref());
 4519            }
 4520        }
 4521
 4522        if project.is_via_collab() {
 4523            title.push_str("");
 4524        } else if project.is_shared() {
 4525            title.push_str("");
 4526        }
 4527
 4528        if let Some(last_title) = self.last_window_title.as_ref()
 4529            && &title == last_title
 4530        {
 4531            return;
 4532        }
 4533        window.set_window_title(&title);
 4534        SystemWindowTabController::update_tab_title(
 4535            cx,
 4536            window.window_handle().window_id(),
 4537            SharedString::from(&title),
 4538        );
 4539        self.last_window_title = Some(title);
 4540    }
 4541
 4542    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4543        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4544        if is_edited != self.window_edited {
 4545            self.window_edited = is_edited;
 4546            window.set_window_edited(self.window_edited)
 4547        }
 4548    }
 4549
 4550    fn update_item_dirty_state(
 4551        &mut self,
 4552        item: &dyn ItemHandle,
 4553        window: &mut Window,
 4554        cx: &mut App,
 4555    ) {
 4556        let is_dirty = item.is_dirty(cx);
 4557        let item_id = item.item_id();
 4558        let was_dirty = self.dirty_items.contains_key(&item_id);
 4559        if is_dirty == was_dirty {
 4560            return;
 4561        }
 4562        if was_dirty {
 4563            self.dirty_items.remove(&item_id);
 4564            self.update_window_edited(window, cx);
 4565            return;
 4566        }
 4567        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4568            let s = item.on_release(
 4569                cx,
 4570                Box::new(move |cx| {
 4571                    window_handle
 4572                        .update(cx, |this, window, cx| {
 4573                            this.dirty_items.remove(&item_id);
 4574                            this.update_window_edited(window, cx)
 4575                        })
 4576                        .ok();
 4577                }),
 4578            );
 4579            self.dirty_items.insert(item_id, s);
 4580            self.update_window_edited(window, cx);
 4581        }
 4582    }
 4583
 4584    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4585        if self.notifications.is_empty() {
 4586            None
 4587        } else {
 4588            Some(
 4589                div()
 4590                    .absolute()
 4591                    .right_3()
 4592                    .bottom_3()
 4593                    .w_112()
 4594                    .h_full()
 4595                    .flex()
 4596                    .flex_col()
 4597                    .justify_end()
 4598                    .gap_2()
 4599                    .children(
 4600                        self.notifications
 4601                            .iter()
 4602                            .map(|(_, notification)| notification.clone().into_any()),
 4603                    ),
 4604            )
 4605        }
 4606    }
 4607
 4608    // RPC handlers
 4609
 4610    fn active_view_for_follower(
 4611        &self,
 4612        follower_project_id: Option<u64>,
 4613        window: &mut Window,
 4614        cx: &mut Context<Self>,
 4615    ) -> Option<proto::View> {
 4616        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4617        let item = item?;
 4618        let leader_id = self
 4619            .pane_for(&*item)
 4620            .and_then(|pane| self.leader_for_pane(&pane));
 4621        let leader_peer_id = match leader_id {
 4622            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4623            Some(CollaboratorId::Agent) | None => None,
 4624        };
 4625
 4626        let item_handle = item.to_followable_item_handle(cx)?;
 4627        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4628        let variant = item_handle.to_state_proto(window, cx)?;
 4629
 4630        if item_handle.is_project_item(window, cx)
 4631            && (follower_project_id.is_none()
 4632                || follower_project_id != self.project.read(cx).remote_id())
 4633        {
 4634            return None;
 4635        }
 4636
 4637        Some(proto::View {
 4638            id: id.to_proto(),
 4639            leader_id: leader_peer_id,
 4640            variant: Some(variant),
 4641            panel_id: panel_id.map(|id| id as i32),
 4642        })
 4643    }
 4644
 4645    fn handle_follow(
 4646        &mut self,
 4647        follower_project_id: Option<u64>,
 4648        window: &mut Window,
 4649        cx: &mut Context<Self>,
 4650    ) -> proto::FollowResponse {
 4651        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4652
 4653        cx.notify();
 4654        proto::FollowResponse {
 4655            // TODO: Remove after version 0.145.x stabilizes.
 4656            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4657            views: active_view.iter().cloned().collect(),
 4658            active_view,
 4659        }
 4660    }
 4661
 4662    fn handle_update_followers(
 4663        &mut self,
 4664        leader_id: PeerId,
 4665        message: proto::UpdateFollowers,
 4666        _window: &mut Window,
 4667        _cx: &mut Context<Self>,
 4668    ) {
 4669        self.leader_updates_tx
 4670            .unbounded_send((leader_id, message))
 4671            .ok();
 4672    }
 4673
 4674    async fn process_leader_update(
 4675        this: &WeakEntity<Self>,
 4676        leader_id: PeerId,
 4677        update: proto::UpdateFollowers,
 4678        cx: &mut AsyncWindowContext,
 4679    ) -> Result<()> {
 4680        match update.variant.context("invalid update")? {
 4681            proto::update_followers::Variant::CreateView(view) => {
 4682                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4683                let should_add_view = this.update(cx, |this, _| {
 4684                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4685                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4686                    } else {
 4687                        anyhow::Ok(false)
 4688                    }
 4689                })??;
 4690
 4691                if should_add_view {
 4692                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4693                }
 4694            }
 4695            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4696                let should_add_view = this.update(cx, |this, _| {
 4697                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4698                        state.active_view_id = update_active_view
 4699                            .view
 4700                            .as_ref()
 4701                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4702
 4703                        if state.active_view_id.is_some_and(|view_id| {
 4704                            !state.items_by_leader_view_id.contains_key(&view_id)
 4705                        }) {
 4706                            anyhow::Ok(true)
 4707                        } else {
 4708                            anyhow::Ok(false)
 4709                        }
 4710                    } else {
 4711                        anyhow::Ok(false)
 4712                    }
 4713                })??;
 4714
 4715                if should_add_view && let Some(view) = update_active_view.view {
 4716                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4717                }
 4718            }
 4719            proto::update_followers::Variant::UpdateView(update_view) => {
 4720                let variant = update_view.variant.context("missing update view variant")?;
 4721                let id = update_view.id.context("missing update view id")?;
 4722                let mut tasks = Vec::new();
 4723                this.update_in(cx, |this, window, cx| {
 4724                    let project = this.project.clone();
 4725                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 4726                        let view_id = ViewId::from_proto(id.clone())?;
 4727                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 4728                            tasks.push(item.view.apply_update_proto(
 4729                                &project,
 4730                                variant.clone(),
 4731                                window,
 4732                                cx,
 4733                            ));
 4734                        }
 4735                    }
 4736                    anyhow::Ok(())
 4737                })??;
 4738                try_join_all(tasks).await.log_err();
 4739            }
 4740        }
 4741        this.update_in(cx, |this, window, cx| {
 4742            this.leader_updated(leader_id, window, cx)
 4743        })?;
 4744        Ok(())
 4745    }
 4746
 4747    async fn add_view_from_leader(
 4748        this: WeakEntity<Self>,
 4749        leader_id: PeerId,
 4750        view: &proto::View,
 4751        cx: &mut AsyncWindowContext,
 4752    ) -> Result<()> {
 4753        let this = this.upgrade().context("workspace dropped")?;
 4754
 4755        let Some(id) = view.id.clone() else {
 4756            anyhow::bail!("no id for view");
 4757        };
 4758        let id = ViewId::from_proto(id)?;
 4759        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 4760
 4761        let pane = this.update(cx, |this, _cx| {
 4762            let state = this
 4763                .follower_states
 4764                .get(&leader_id.into())
 4765                .context("stopped following")?;
 4766            anyhow::Ok(state.pane().clone())
 4767        })??;
 4768        let existing_item = pane.update_in(cx, |pane, window, cx| {
 4769            let client = this.read(cx).client().clone();
 4770            pane.items().find_map(|item| {
 4771                let item = item.to_followable_item_handle(cx)?;
 4772                if item.remote_id(&client, window, cx) == Some(id) {
 4773                    Some(item)
 4774                } else {
 4775                    None
 4776                }
 4777            })
 4778        })?;
 4779        let item = if let Some(existing_item) = existing_item {
 4780            existing_item
 4781        } else {
 4782            let variant = view.variant.clone();
 4783            anyhow::ensure!(variant.is_some(), "missing view variant");
 4784
 4785            let task = cx.update(|window, cx| {
 4786                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 4787            })?;
 4788
 4789            let Some(task) = task else {
 4790                anyhow::bail!(
 4791                    "failed to construct view from leader (maybe from a different version of zed?)"
 4792                );
 4793            };
 4794
 4795            let mut new_item = task.await?;
 4796            pane.update_in(cx, |pane, window, cx| {
 4797                let mut item_to_remove = None;
 4798                for (ix, item) in pane.items().enumerate() {
 4799                    if let Some(item) = item.to_followable_item_handle(cx) {
 4800                        match new_item.dedup(item.as_ref(), window, cx) {
 4801                            Some(item::Dedup::KeepExisting) => {
 4802                                new_item =
 4803                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 4804                                break;
 4805                            }
 4806                            Some(item::Dedup::ReplaceExisting) => {
 4807                                item_to_remove = Some((ix, item.item_id()));
 4808                                break;
 4809                            }
 4810                            None => {}
 4811                        }
 4812                    }
 4813                }
 4814
 4815                if let Some((ix, id)) = item_to_remove {
 4816                    pane.remove_item(id, false, false, window, cx);
 4817                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 4818                }
 4819            })?;
 4820
 4821            new_item
 4822        };
 4823
 4824        this.update_in(cx, |this, window, cx| {
 4825            let state = this.follower_states.get_mut(&leader_id.into())?;
 4826            item.set_leader_id(Some(leader_id.into()), window, cx);
 4827            state.items_by_leader_view_id.insert(
 4828                id,
 4829                FollowerView {
 4830                    view: item,
 4831                    location: panel_id,
 4832                },
 4833            );
 4834
 4835            Some(())
 4836        })?;
 4837
 4838        Ok(())
 4839    }
 4840
 4841    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4842        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 4843            return;
 4844        };
 4845
 4846        if let Some(agent_location) = self.project.read(cx).agent_location() {
 4847            let buffer_entity_id = agent_location.buffer.entity_id();
 4848            let view_id = ViewId {
 4849                creator: CollaboratorId::Agent,
 4850                id: buffer_entity_id.as_u64(),
 4851            };
 4852            follower_state.active_view_id = Some(view_id);
 4853
 4854            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 4855                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 4856                hash_map::Entry::Vacant(entry) => {
 4857                    let existing_view =
 4858                        follower_state
 4859                            .center_pane
 4860                            .read(cx)
 4861                            .items()
 4862                            .find_map(|item| {
 4863                                let item = item.to_followable_item_handle(cx)?;
 4864                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 4865                                    && item.project_item_model_ids(cx).as_slice()
 4866                                        == [buffer_entity_id]
 4867                                {
 4868                                    Some(item)
 4869                                } else {
 4870                                    None
 4871                                }
 4872                            });
 4873                    let view = existing_view.or_else(|| {
 4874                        agent_location.buffer.upgrade().and_then(|buffer| {
 4875                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 4876                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 4877                            })?
 4878                            .to_followable_item_handle(cx)
 4879                        })
 4880                    });
 4881
 4882                    view.map(|view| {
 4883                        entry.insert(FollowerView {
 4884                            view,
 4885                            location: None,
 4886                        })
 4887                    })
 4888                }
 4889            };
 4890
 4891            if let Some(item) = item {
 4892                item.view
 4893                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 4894                item.view
 4895                    .update_agent_location(agent_location.position, window, cx);
 4896            }
 4897        } else {
 4898            follower_state.active_view_id = None;
 4899        }
 4900
 4901        self.leader_updated(CollaboratorId::Agent, window, cx);
 4902    }
 4903
 4904    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 4905        let mut is_project_item = true;
 4906        let mut update = proto::UpdateActiveView::default();
 4907        if window.is_window_active() {
 4908            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 4909
 4910            if let Some(item) = active_item
 4911                && item.item_focus_handle(cx).contains_focused(window, cx)
 4912            {
 4913                let leader_id = self
 4914                    .pane_for(&*item)
 4915                    .and_then(|pane| self.leader_for_pane(&pane));
 4916                let leader_peer_id = match leader_id {
 4917                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4918                    Some(CollaboratorId::Agent) | None => None,
 4919                };
 4920
 4921                if let Some(item) = item.to_followable_item_handle(cx) {
 4922                    let id = item
 4923                        .remote_id(&self.app_state.client, window, cx)
 4924                        .map(|id| id.to_proto());
 4925
 4926                    if let Some(id) = id
 4927                        && let Some(variant) = item.to_state_proto(window, cx)
 4928                    {
 4929                        let view = Some(proto::View {
 4930                            id: id.clone(),
 4931                            leader_id: leader_peer_id,
 4932                            variant: Some(variant),
 4933                            panel_id: panel_id.map(|id| id as i32),
 4934                        });
 4935
 4936                        is_project_item = item.is_project_item(window, cx);
 4937                        update = proto::UpdateActiveView {
 4938                            view,
 4939                            // TODO: Remove after version 0.145.x stabilizes.
 4940                            id,
 4941                            leader_id: leader_peer_id,
 4942                        };
 4943                    };
 4944                }
 4945            }
 4946        }
 4947
 4948        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 4949        if active_view_id != self.last_active_view_id.as_ref() {
 4950            self.last_active_view_id = active_view_id.cloned();
 4951            self.update_followers(
 4952                is_project_item,
 4953                proto::update_followers::Variant::UpdateActiveView(update),
 4954                window,
 4955                cx,
 4956            );
 4957        }
 4958    }
 4959
 4960    fn active_item_for_followers(
 4961        &self,
 4962        window: &mut Window,
 4963        cx: &mut App,
 4964    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 4965        let mut active_item = None;
 4966        let mut panel_id = None;
 4967        for dock in self.all_docks() {
 4968            if dock.focus_handle(cx).contains_focused(window, cx)
 4969                && let Some(panel) = dock.read(cx).active_panel()
 4970                && let Some(pane) = panel.pane(cx)
 4971                && let Some(item) = pane.read(cx).active_item()
 4972            {
 4973                active_item = Some(item);
 4974                panel_id = panel.remote_id();
 4975                break;
 4976            }
 4977        }
 4978
 4979        if active_item.is_none() {
 4980            active_item = self.active_pane().read(cx).active_item();
 4981        }
 4982        (active_item, panel_id)
 4983    }
 4984
 4985    fn update_followers(
 4986        &self,
 4987        project_only: bool,
 4988        update: proto::update_followers::Variant,
 4989        _: &mut Window,
 4990        cx: &mut App,
 4991    ) -> Option<()> {
 4992        // If this update only applies to for followers in the current project,
 4993        // then skip it unless this project is shared. If it applies to all
 4994        // followers, regardless of project, then set `project_id` to none,
 4995        // indicating that it goes to all followers.
 4996        let project_id = if project_only {
 4997            Some(self.project.read(cx).remote_id()?)
 4998        } else {
 4999            None
 5000        };
 5001        self.app_state().workspace_store.update(cx, |store, cx| {
 5002            store.update_followers(project_id, update, cx)
 5003        })
 5004    }
 5005
 5006    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5007        self.follower_states.iter().find_map(|(leader_id, state)| {
 5008            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5009                Some(*leader_id)
 5010            } else {
 5011                None
 5012            }
 5013        })
 5014    }
 5015
 5016    fn leader_updated(
 5017        &mut self,
 5018        leader_id: impl Into<CollaboratorId>,
 5019        window: &mut Window,
 5020        cx: &mut Context<Self>,
 5021    ) -> Option<Box<dyn ItemHandle>> {
 5022        cx.notify();
 5023
 5024        let leader_id = leader_id.into();
 5025        let (panel_id, item) = match leader_id {
 5026            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5027            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5028        };
 5029
 5030        let state = self.follower_states.get(&leader_id)?;
 5031        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5032        let pane;
 5033        if let Some(panel_id) = panel_id {
 5034            pane = self
 5035                .activate_panel_for_proto_id(panel_id, window, cx)?
 5036                .pane(cx)?;
 5037            let state = self.follower_states.get_mut(&leader_id)?;
 5038            state.dock_pane = Some(pane.clone());
 5039        } else {
 5040            pane = state.center_pane.clone();
 5041            let state = self.follower_states.get_mut(&leader_id)?;
 5042            if let Some(dock_pane) = state.dock_pane.take() {
 5043                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5044            }
 5045        }
 5046
 5047        pane.update(cx, |pane, cx| {
 5048            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5049            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5050                pane.activate_item(index, false, false, window, cx);
 5051            } else {
 5052                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5053            }
 5054
 5055            if focus_active_item {
 5056                pane.focus_active_item(window, cx)
 5057            }
 5058        });
 5059
 5060        Some(item)
 5061    }
 5062
 5063    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5064        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5065        let active_view_id = state.active_view_id?;
 5066        Some(
 5067            state
 5068                .items_by_leader_view_id
 5069                .get(&active_view_id)?
 5070                .view
 5071                .boxed_clone(),
 5072        )
 5073    }
 5074
 5075    fn active_item_for_peer(
 5076        &self,
 5077        peer_id: PeerId,
 5078        window: &mut Window,
 5079        cx: &mut Context<Self>,
 5080    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5081        let call = self.active_call()?;
 5082        let room = call.read(cx).room()?.read(cx);
 5083        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5084        let leader_in_this_app;
 5085        let leader_in_this_project;
 5086        match participant.location {
 5087            call::ParticipantLocation::SharedProject { project_id } => {
 5088                leader_in_this_app = true;
 5089                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5090            }
 5091            call::ParticipantLocation::UnsharedProject => {
 5092                leader_in_this_app = true;
 5093                leader_in_this_project = false;
 5094            }
 5095            call::ParticipantLocation::External => {
 5096                leader_in_this_app = false;
 5097                leader_in_this_project = false;
 5098            }
 5099        };
 5100        let state = self.follower_states.get(&peer_id.into())?;
 5101        let mut item_to_activate = None;
 5102        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5103            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5104                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5105            {
 5106                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5107            }
 5108        } else if let Some(shared_screen) =
 5109            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5110        {
 5111            item_to_activate = Some((None, Box::new(shared_screen)));
 5112        }
 5113        item_to_activate
 5114    }
 5115
 5116    fn shared_screen_for_peer(
 5117        &self,
 5118        peer_id: PeerId,
 5119        pane: &Entity<Pane>,
 5120        window: &mut Window,
 5121        cx: &mut App,
 5122    ) -> Option<Entity<SharedScreen>> {
 5123        let call = self.active_call()?;
 5124        let room = call.read(cx).room()?.clone();
 5125        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5126        let track = participant.video_tracks.values().next()?.clone();
 5127        let user = participant.user.clone();
 5128
 5129        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5130            if item.read(cx).peer_id == peer_id {
 5131                return Some(item);
 5132            }
 5133        }
 5134
 5135        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5136    }
 5137
 5138    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5139        if window.is_window_active() {
 5140            self.update_active_view_for_followers(window, cx);
 5141
 5142            if let Some(database_id) = self.database_id {
 5143                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5144                    .detach();
 5145            }
 5146        } else {
 5147            for pane in &self.panes {
 5148                pane.update(cx, |pane, cx| {
 5149                    if let Some(item) = pane.active_item() {
 5150                        item.workspace_deactivated(window, cx);
 5151                    }
 5152                    for item in pane.items() {
 5153                        if matches!(
 5154                            item.workspace_settings(cx).autosave,
 5155                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5156                        ) {
 5157                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5158                                .detach_and_log_err(cx);
 5159                        }
 5160                    }
 5161                });
 5162            }
 5163        }
 5164    }
 5165
 5166    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5167        self.active_call.as_ref().map(|(call, _)| call)
 5168    }
 5169
 5170    fn on_active_call_event(
 5171        &mut self,
 5172        _: &Entity<ActiveCall>,
 5173        event: &call::room::Event,
 5174        window: &mut Window,
 5175        cx: &mut Context<Self>,
 5176    ) {
 5177        match event {
 5178            call::room::Event::ParticipantLocationChanged { participant_id }
 5179            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5180                self.leader_updated(participant_id, window, cx);
 5181            }
 5182            _ => {}
 5183        }
 5184    }
 5185
 5186    pub fn database_id(&self) -> Option<WorkspaceId> {
 5187        self.database_id
 5188    }
 5189
 5190    pub fn session_id(&self) -> Option<String> {
 5191        self.session_id.clone()
 5192    }
 5193
 5194    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5195        let project = self.project().read(cx);
 5196        project
 5197            .visible_worktrees(cx)
 5198            .map(|worktree| worktree.read(cx).abs_path())
 5199            .collect::<Vec<_>>()
 5200    }
 5201
 5202    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5203        match member {
 5204            Member::Axis(PaneAxis { members, .. }) => {
 5205                for child in members.iter() {
 5206                    self.remove_panes(child.clone(), window, cx)
 5207                }
 5208            }
 5209            Member::Pane(pane) => {
 5210                self.force_remove_pane(&pane, &None, window, cx);
 5211            }
 5212        }
 5213    }
 5214
 5215    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5216        self.session_id.take();
 5217        self.serialize_workspace_internal(window, cx)
 5218    }
 5219
 5220    fn force_remove_pane(
 5221        &mut self,
 5222        pane: &Entity<Pane>,
 5223        focus_on: &Option<Entity<Pane>>,
 5224        window: &mut Window,
 5225        cx: &mut Context<Workspace>,
 5226    ) {
 5227        self.panes.retain(|p| p != pane);
 5228        if let Some(focus_on) = focus_on {
 5229            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5230        } else if self.active_pane() == pane {
 5231            self.panes
 5232                .last()
 5233                .unwrap()
 5234                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5235        }
 5236        if self.last_active_center_pane == Some(pane.downgrade()) {
 5237            self.last_active_center_pane = None;
 5238        }
 5239        cx.notify();
 5240    }
 5241
 5242    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5243        if self._schedule_serialize_workspace.is_none() {
 5244            self._schedule_serialize_workspace =
 5245                Some(cx.spawn_in(window, async move |this, cx| {
 5246                    cx.background_executor()
 5247                        .timer(SERIALIZATION_THROTTLE_TIME)
 5248                        .await;
 5249                    this.update_in(cx, |this, window, cx| {
 5250                        this.serialize_workspace_internal(window, cx).detach();
 5251                        this._schedule_serialize_workspace.take();
 5252                    })
 5253                    .log_err();
 5254                }));
 5255        }
 5256    }
 5257
 5258    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5259        let Some(database_id) = self.database_id() else {
 5260            return Task::ready(());
 5261        };
 5262
 5263        fn serialize_pane_handle(
 5264            pane_handle: &Entity<Pane>,
 5265            window: &mut Window,
 5266            cx: &mut App,
 5267        ) -> SerializedPane {
 5268            let (items, active, pinned_count) = {
 5269                let pane = pane_handle.read(cx);
 5270                let active_item_id = pane.active_item().map(|item| item.item_id());
 5271                (
 5272                    pane.items()
 5273                        .filter_map(|handle| {
 5274                            let handle = handle.to_serializable_item_handle(cx)?;
 5275
 5276                            Some(SerializedItem {
 5277                                kind: Arc::from(handle.serialized_item_kind()),
 5278                                item_id: handle.item_id().as_u64(),
 5279                                active: Some(handle.item_id()) == active_item_id,
 5280                                preview: pane.is_active_preview_item(handle.item_id()),
 5281                            })
 5282                        })
 5283                        .collect::<Vec<_>>(),
 5284                    pane.has_focus(window, cx),
 5285                    pane.pinned_count(),
 5286                )
 5287            };
 5288
 5289            SerializedPane::new(items, active, pinned_count)
 5290        }
 5291
 5292        fn build_serialized_pane_group(
 5293            pane_group: &Member,
 5294            window: &mut Window,
 5295            cx: &mut App,
 5296        ) -> SerializedPaneGroup {
 5297            match pane_group {
 5298                Member::Axis(PaneAxis {
 5299                    axis,
 5300                    members,
 5301                    flexes,
 5302                    bounding_boxes: _,
 5303                }) => SerializedPaneGroup::Group {
 5304                    axis: SerializedAxis(*axis),
 5305                    children: members
 5306                        .iter()
 5307                        .map(|member| build_serialized_pane_group(member, window, cx))
 5308                        .collect::<Vec<_>>(),
 5309                    flexes: Some(flexes.lock().clone()),
 5310                },
 5311                Member::Pane(pane_handle) => {
 5312                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5313                }
 5314            }
 5315        }
 5316
 5317        fn build_serialized_docks(
 5318            this: &Workspace,
 5319            window: &mut Window,
 5320            cx: &mut App,
 5321        ) -> DockStructure {
 5322            let left_dock = this.left_dock.read(cx);
 5323            let left_visible = left_dock.is_open();
 5324            let left_active_panel = left_dock
 5325                .active_panel()
 5326                .map(|panel| panel.persistent_name().to_string());
 5327            let left_dock_zoom = left_dock
 5328                .active_panel()
 5329                .map(|panel| panel.is_zoomed(window, cx))
 5330                .unwrap_or(false);
 5331
 5332            let right_dock = this.right_dock.read(cx);
 5333            let right_visible = right_dock.is_open();
 5334            let right_active_panel = right_dock
 5335                .active_panel()
 5336                .map(|panel| panel.persistent_name().to_string());
 5337            let right_dock_zoom = right_dock
 5338                .active_panel()
 5339                .map(|panel| panel.is_zoomed(window, cx))
 5340                .unwrap_or(false);
 5341
 5342            let bottom_dock = this.bottom_dock.read(cx);
 5343            let bottom_visible = bottom_dock.is_open();
 5344            let bottom_active_panel = bottom_dock
 5345                .active_panel()
 5346                .map(|panel| panel.persistent_name().to_string());
 5347            let bottom_dock_zoom = bottom_dock
 5348                .active_panel()
 5349                .map(|panel| panel.is_zoomed(window, cx))
 5350                .unwrap_or(false);
 5351
 5352            DockStructure {
 5353                left: DockData {
 5354                    visible: left_visible,
 5355                    active_panel: left_active_panel,
 5356                    zoom: left_dock_zoom,
 5357                },
 5358                right: DockData {
 5359                    visible: right_visible,
 5360                    active_panel: right_active_panel,
 5361                    zoom: right_dock_zoom,
 5362                },
 5363                bottom: DockData {
 5364                    visible: bottom_visible,
 5365                    active_panel: bottom_active_panel,
 5366                    zoom: bottom_dock_zoom,
 5367                },
 5368            }
 5369        }
 5370
 5371        match self.serialize_workspace_location(cx) {
 5372            WorkspaceLocation::Location(location, paths) => {
 5373                let breakpoints = self.project.update(cx, |project, cx| {
 5374                    project
 5375                        .breakpoint_store()
 5376                        .read(cx)
 5377                        .all_source_breakpoints(cx)
 5378                });
 5379                let user_toolchains = self
 5380                    .project
 5381                    .read(cx)
 5382                    .user_toolchains(cx)
 5383                    .unwrap_or_default();
 5384
 5385                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5386                let docks = build_serialized_docks(self, window, cx);
 5387                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5388
 5389                let serialized_workspace = SerializedWorkspace {
 5390                    id: database_id,
 5391                    location,
 5392                    paths,
 5393                    center_group,
 5394                    window_bounds,
 5395                    display: Default::default(),
 5396                    docks,
 5397                    centered_layout: self.centered_layout,
 5398                    session_id: self.session_id.clone(),
 5399                    breakpoints,
 5400                    window_id: Some(window.window_handle().window_id().as_u64()),
 5401                    user_toolchains,
 5402                };
 5403
 5404                window.spawn(cx, async move |_| {
 5405                    persistence::DB.save_workspace(serialized_workspace).await;
 5406                })
 5407            }
 5408            WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
 5409                persistence::DB
 5410                    .set_session_id(database_id, None)
 5411                    .await
 5412                    .log_err();
 5413            }),
 5414            WorkspaceLocation::None => Task::ready(()),
 5415        }
 5416    }
 5417
 5418    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5419        let paths = PathList::new(&self.root_paths(cx));
 5420        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5421            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 5422        } else if self.project.read(cx).is_local() {
 5423            if !paths.is_empty() {
 5424                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5425            } else {
 5426                WorkspaceLocation::DetachFromSession
 5427            }
 5428        } else {
 5429            WorkspaceLocation::None
 5430        }
 5431    }
 5432
 5433    fn update_history(&self, cx: &mut App) {
 5434        let Some(id) = self.database_id() else {
 5435            return;
 5436        };
 5437        if !self.project.read(cx).is_local() {
 5438            return;
 5439        }
 5440        if let Some(manager) = HistoryManager::global(cx) {
 5441            let paths = PathList::new(&self.root_paths(cx));
 5442            manager.update(cx, |this, cx| {
 5443                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5444            });
 5445        }
 5446    }
 5447
 5448    async fn serialize_items(
 5449        this: &WeakEntity<Self>,
 5450        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5451        cx: &mut AsyncWindowContext,
 5452    ) -> Result<()> {
 5453        const CHUNK_SIZE: usize = 200;
 5454
 5455        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5456
 5457        while let Some(items_received) = serializable_items.next().await {
 5458            let unique_items =
 5459                items_received
 5460                    .into_iter()
 5461                    .fold(HashMap::default(), |mut acc, item| {
 5462                        acc.entry(item.item_id()).or_insert(item);
 5463                        acc
 5464                    });
 5465
 5466            // We use into_iter() here so that the references to the items are moved into
 5467            // the tasks and not kept alive while we're sleeping.
 5468            for (_, item) in unique_items.into_iter() {
 5469                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5470                    item.serialize(workspace, false, window, cx)
 5471                }) {
 5472                    cx.background_spawn(async move { task.await.log_err() })
 5473                        .detach();
 5474                }
 5475            }
 5476
 5477            cx.background_executor()
 5478                .timer(SERIALIZATION_THROTTLE_TIME)
 5479                .await;
 5480        }
 5481
 5482        Ok(())
 5483    }
 5484
 5485    pub(crate) fn enqueue_item_serialization(
 5486        &mut self,
 5487        item: Box<dyn SerializableItemHandle>,
 5488    ) -> Result<()> {
 5489        self.serializable_items_tx
 5490            .unbounded_send(item)
 5491            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5492    }
 5493
 5494    pub(crate) fn load_workspace(
 5495        serialized_workspace: SerializedWorkspace,
 5496        paths_to_open: Vec<Option<ProjectPath>>,
 5497        window: &mut Window,
 5498        cx: &mut Context<Workspace>,
 5499    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5500        cx.spawn_in(window, async move |workspace, cx| {
 5501            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5502
 5503            let mut center_group = None;
 5504            let mut center_items = None;
 5505
 5506            // Traverse the splits tree and add to things
 5507            if let Some((group, active_pane, items)) = serialized_workspace
 5508                .center_group
 5509                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5510                .await
 5511            {
 5512                center_items = Some(items);
 5513                center_group = Some((group, active_pane))
 5514            }
 5515
 5516            let mut items_by_project_path = HashMap::default();
 5517            let mut item_ids_by_kind = HashMap::default();
 5518            let mut all_deserialized_items = Vec::default();
 5519            cx.update(|_, cx| {
 5520                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5521                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5522                        item_ids_by_kind
 5523                            .entry(serializable_item_handle.serialized_item_kind())
 5524                            .or_insert(Vec::new())
 5525                            .push(item.item_id().as_u64() as ItemId);
 5526                    }
 5527
 5528                    if let Some(project_path) = item.project_path(cx) {
 5529                        items_by_project_path.insert(project_path, item.clone());
 5530                    }
 5531                    all_deserialized_items.push(item);
 5532                }
 5533            })?;
 5534
 5535            let opened_items = paths_to_open
 5536                .into_iter()
 5537                .map(|path_to_open| {
 5538                    path_to_open
 5539                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5540                })
 5541                .collect::<Vec<_>>();
 5542
 5543            // Remove old panes from workspace panes list
 5544            workspace.update_in(cx, |workspace, window, cx| {
 5545                if let Some((center_group, active_pane)) = center_group {
 5546                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5547
 5548                    // Swap workspace center group
 5549                    workspace.center = PaneGroup::with_root(center_group);
 5550                    if let Some(active_pane) = active_pane {
 5551                        workspace.set_active_pane(&active_pane, window, cx);
 5552                        cx.focus_self(window);
 5553                    } else {
 5554                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5555                    }
 5556                }
 5557
 5558                let docks = serialized_workspace.docks;
 5559
 5560                for (dock, serialized_dock) in [
 5561                    (&mut workspace.right_dock, docks.right),
 5562                    (&mut workspace.left_dock, docks.left),
 5563                    (&mut workspace.bottom_dock, docks.bottom),
 5564                ]
 5565                .iter_mut()
 5566                {
 5567                    dock.update(cx, |dock, cx| {
 5568                        dock.serialized_dock = Some(serialized_dock.clone());
 5569                        dock.restore_state(window, cx);
 5570                    });
 5571                }
 5572
 5573                cx.notify();
 5574            })?;
 5575
 5576            let _ = project
 5577                .update(cx, |project, cx| {
 5578                    project
 5579                        .breakpoint_store()
 5580                        .update(cx, |breakpoint_store, cx| {
 5581                            breakpoint_store
 5582                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5583                        })
 5584                })?
 5585                .await;
 5586
 5587            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5588            // after loading the items, we might have different items and in order to avoid
 5589            // the database filling up, we delete items that haven't been loaded now.
 5590            //
 5591            // The items that have been loaded, have been saved after they've been added to the workspace.
 5592            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5593                item_ids_by_kind
 5594                    .into_iter()
 5595                    .map(|(item_kind, loaded_items)| {
 5596                        SerializableItemRegistry::cleanup(
 5597                            item_kind,
 5598                            serialized_workspace.id,
 5599                            loaded_items,
 5600                            window,
 5601                            cx,
 5602                        )
 5603                        .log_err()
 5604                    })
 5605                    .collect::<Vec<_>>()
 5606            })?;
 5607
 5608            futures::future::join_all(clean_up_tasks).await;
 5609
 5610            workspace
 5611                .update_in(cx, |workspace, window, cx| {
 5612                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5613                    workspace.serialize_workspace_internal(window, cx).detach();
 5614
 5615                    // Ensure that we mark the window as edited if we did load dirty items
 5616                    workspace.update_window_edited(window, cx);
 5617                })
 5618                .ok();
 5619
 5620            Ok(opened_items)
 5621        })
 5622    }
 5623
 5624    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5625        self.add_workspace_actions_listeners(div, window, cx)
 5626            .on_action(cx.listener(
 5627                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 5628                    for action in &action_sequence.0 {
 5629                        window.dispatch_action(action.boxed_clone(), cx);
 5630                    }
 5631                },
 5632            ))
 5633            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5634            .on_action(cx.listener(Self::close_all_items_and_panes))
 5635            .on_action(cx.listener(Self::save_all))
 5636            .on_action(cx.listener(Self::send_keystrokes))
 5637            .on_action(cx.listener(Self::add_folder_to_project))
 5638            .on_action(cx.listener(Self::follow_next_collaborator))
 5639            .on_action(cx.listener(Self::close_window))
 5640            .on_action(cx.listener(Self::activate_pane_at_index))
 5641            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5642            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5643            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 5644            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5645                let pane = workspace.active_pane().clone();
 5646                workspace.unfollow_in_pane(&pane, window, cx);
 5647            }))
 5648            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5649                workspace
 5650                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5651                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5652            }))
 5653            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5654                workspace
 5655                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5656                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5657            }))
 5658            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5659                workspace
 5660                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5661                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5662            }))
 5663            .on_action(
 5664                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5665                    workspace.activate_previous_pane(window, cx)
 5666                }),
 5667            )
 5668            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5669                workspace.activate_next_pane(window, cx)
 5670            }))
 5671            .on_action(
 5672                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5673                    workspace.activate_next_window(cx)
 5674                }),
 5675            )
 5676            .on_action(
 5677                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5678                    workspace.activate_previous_window(cx)
 5679                }),
 5680            )
 5681            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5682                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5683            }))
 5684            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5685                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5686            }))
 5687            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5688                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5689            }))
 5690            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 5691                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 5692            }))
 5693            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5694                workspace.activate_next_pane(window, cx)
 5695            }))
 5696            .on_action(cx.listener(
 5697                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 5698                    workspace.move_item_to_pane_in_direction(action, window, cx)
 5699                },
 5700            ))
 5701            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 5702                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 5703            }))
 5704            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 5705                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 5706            }))
 5707            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 5708                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 5709            }))
 5710            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 5711                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 5712            }))
 5713            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 5714                workspace.move_pane_to_border(SplitDirection::Left, cx)
 5715            }))
 5716            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 5717                workspace.move_pane_to_border(SplitDirection::Right, cx)
 5718            }))
 5719            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 5720                workspace.move_pane_to_border(SplitDirection::Up, cx)
 5721            }))
 5722            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 5723                workspace.move_pane_to_border(SplitDirection::Down, cx)
 5724            }))
 5725            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 5726                this.toggle_dock(DockPosition::Left, window, cx);
 5727            }))
 5728            .on_action(cx.listener(
 5729                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 5730                    workspace.toggle_dock(DockPosition::Right, window, cx);
 5731                },
 5732            ))
 5733            .on_action(cx.listener(
 5734                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 5735                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 5736                },
 5737            ))
 5738            .on_action(cx.listener(
 5739                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 5740                    if !workspace.close_active_dock(window, cx) {
 5741                        cx.propagate();
 5742                    }
 5743                },
 5744            ))
 5745            .on_action(
 5746                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 5747                    workspace.close_all_docks(window, cx);
 5748                }),
 5749            )
 5750            .on_action(cx.listener(
 5751                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 5752                    workspace.clear_all_notifications(cx);
 5753                },
 5754            ))
 5755            .on_action(cx.listener(
 5756                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 5757                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 5758                        workspace.suppress_notification(&notification_id, cx);
 5759                    }
 5760                },
 5761            ))
 5762            .on_action(cx.listener(
 5763                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 5764                    workspace.reopen_closed_item(window, cx).detach();
 5765                },
 5766            ))
 5767            .on_action(cx.listener(
 5768                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 5769                    for dock in workspace.all_docks() {
 5770                        if dock.focus_handle(cx).contains_focused(window, cx) {
 5771                            let Some(panel) = dock.read(cx).active_panel() else {
 5772                                return;
 5773                            };
 5774
 5775                            // Set to `None`, then the size will fall back to the default.
 5776                            panel.clone().set_size(None, window, cx);
 5777
 5778                            return;
 5779                        }
 5780                    }
 5781                },
 5782            ))
 5783            .on_action(cx.listener(
 5784                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 5785                    for dock in workspace.all_docks() {
 5786                        if let Some(panel) = dock.read(cx).visible_panel() {
 5787                            // Set to `None`, then the size will fall back to the default.
 5788                            panel.clone().set_size(None, window, cx);
 5789                        }
 5790                    }
 5791                },
 5792            ))
 5793            .on_action(cx.listener(
 5794                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 5795                    adjust_active_dock_size_by_px(
 5796                        px_with_ui_font_fallback(act.px, cx),
 5797                        workspace,
 5798                        window,
 5799                        cx,
 5800                    );
 5801                },
 5802            ))
 5803            .on_action(cx.listener(
 5804                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 5805                    adjust_active_dock_size_by_px(
 5806                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5807                        workspace,
 5808                        window,
 5809                        cx,
 5810                    );
 5811                },
 5812            ))
 5813            .on_action(cx.listener(
 5814                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 5815                    adjust_open_docks_size_by_px(
 5816                        px_with_ui_font_fallback(act.px, cx),
 5817                        workspace,
 5818                        window,
 5819                        cx,
 5820                    );
 5821                },
 5822            ))
 5823            .on_action(cx.listener(
 5824                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 5825                    adjust_open_docks_size_by_px(
 5826                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5827                        workspace,
 5828                        window,
 5829                        cx,
 5830                    );
 5831                },
 5832            ))
 5833            .on_action(cx.listener(Workspace::toggle_centered_layout))
 5834            .on_action(cx.listener(Workspace::cancel))
 5835    }
 5836
 5837    #[cfg(any(test, feature = "test-support"))]
 5838    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 5839        use node_runtime::NodeRuntime;
 5840        use session::Session;
 5841
 5842        let client = project.read(cx).client();
 5843        let user_store = project.read(cx).user_store();
 5844        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 5845        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 5846        window.activate_window();
 5847        let app_state = Arc::new(AppState {
 5848            languages: project.read(cx).languages().clone(),
 5849            workspace_store,
 5850            client,
 5851            user_store,
 5852            fs: project.read(cx).fs().clone(),
 5853            build_window_options: |_, _| Default::default(),
 5854            node_runtime: NodeRuntime::unavailable(),
 5855            session,
 5856        });
 5857        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 5858        workspace
 5859            .active_pane
 5860            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5861        workspace
 5862    }
 5863
 5864    pub fn register_action<A: Action>(
 5865        &mut self,
 5866        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 5867    ) -> &mut Self {
 5868        let callback = Arc::new(callback);
 5869
 5870        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 5871            let callback = callback.clone();
 5872            div.on_action(cx.listener(move |workspace, event, window, cx| {
 5873                (callback)(workspace, event, window, cx)
 5874            }))
 5875        }));
 5876        self
 5877    }
 5878    pub fn register_action_renderer(
 5879        &mut self,
 5880        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 5881    ) -> &mut Self {
 5882        self.workspace_actions.push(Box::new(callback));
 5883        self
 5884    }
 5885
 5886    fn add_workspace_actions_listeners(
 5887        &self,
 5888        mut div: Div,
 5889        window: &mut Window,
 5890        cx: &mut Context<Self>,
 5891    ) -> Div {
 5892        for action in self.workspace_actions.iter() {
 5893            div = (action)(div, self, window, cx)
 5894        }
 5895        div
 5896    }
 5897
 5898    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 5899        self.modal_layer.read(cx).has_active_modal()
 5900    }
 5901
 5902    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 5903        self.modal_layer.read(cx).active_modal()
 5904    }
 5905
 5906    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 5907    where
 5908        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 5909    {
 5910        self.modal_layer.update(cx, |modal_layer, cx| {
 5911            modal_layer.toggle_modal(window, cx, build)
 5912        })
 5913    }
 5914
 5915    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 5916        self.modal_layer
 5917            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 5918    }
 5919
 5920    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 5921        self.toast_layer
 5922            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 5923    }
 5924
 5925    pub fn toggle_centered_layout(
 5926        &mut self,
 5927        _: &ToggleCenteredLayout,
 5928        _: &mut Window,
 5929        cx: &mut Context<Self>,
 5930    ) {
 5931        self.centered_layout = !self.centered_layout;
 5932        if let Some(database_id) = self.database_id() {
 5933            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 5934                .detach_and_log_err(cx);
 5935        }
 5936        cx.notify();
 5937    }
 5938
 5939    fn adjust_padding(padding: Option<f32>) -> f32 {
 5940        padding
 5941            .unwrap_or(Self::DEFAULT_PADDING)
 5942            .clamp(0.0, Self::MAX_PADDING)
 5943    }
 5944
 5945    fn render_dock(
 5946        &self,
 5947        position: DockPosition,
 5948        dock: &Entity<Dock>,
 5949        window: &mut Window,
 5950        cx: &mut App,
 5951    ) -> Option<Div> {
 5952        if self.zoomed_position == Some(position) {
 5953            return None;
 5954        }
 5955
 5956        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 5957            let pane = panel.pane(cx)?;
 5958            let follower_states = &self.follower_states;
 5959            leader_border_for_pane(follower_states, &pane, window, cx)
 5960        });
 5961
 5962        Some(
 5963            div()
 5964                .flex()
 5965                .flex_none()
 5966                .overflow_hidden()
 5967                .child(dock.clone())
 5968                .children(leader_border),
 5969        )
 5970    }
 5971
 5972    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 5973        window.root().flatten()
 5974    }
 5975
 5976    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 5977        self.zoomed.as_ref()
 5978    }
 5979
 5980    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 5981        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 5982            return;
 5983        };
 5984        let windows = cx.windows();
 5985        let next_window =
 5986            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 5987                || {
 5988                    windows
 5989                        .iter()
 5990                        .cycle()
 5991                        .skip_while(|window| window.window_id() != current_window_id)
 5992                        .nth(1)
 5993                },
 5994            );
 5995
 5996        if let Some(window) = next_window {
 5997            window
 5998                .update(cx, |_, window, _| window.activate_window())
 5999                .ok();
 6000        }
 6001    }
 6002
 6003    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6004        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6005            return;
 6006        };
 6007        let windows = cx.windows();
 6008        let prev_window =
 6009            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6010                || {
 6011                    windows
 6012                        .iter()
 6013                        .rev()
 6014                        .cycle()
 6015                        .skip_while(|window| window.window_id() != current_window_id)
 6016                        .nth(1)
 6017                },
 6018            );
 6019
 6020        if let Some(window) = prev_window {
 6021            window
 6022                .update(cx, |_, window, _| window.activate_window())
 6023                .ok();
 6024        }
 6025    }
 6026
 6027    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6028        if cx.stop_active_drag(window) {
 6029        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6030            dismiss_app_notification(&notification_id, cx);
 6031        } else {
 6032            cx.propagate();
 6033        }
 6034    }
 6035
 6036    fn adjust_dock_size_by_px(
 6037        &mut self,
 6038        panel_size: Pixels,
 6039        dock_pos: DockPosition,
 6040        px: Pixels,
 6041        window: &mut Window,
 6042        cx: &mut Context<Self>,
 6043    ) {
 6044        match dock_pos {
 6045            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6046            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6047            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6048        }
 6049    }
 6050
 6051    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6052        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6053
 6054        self.left_dock.update(cx, |left_dock, cx| {
 6055            if WorkspaceSettings::get_global(cx)
 6056                .resize_all_panels_in_dock
 6057                .contains(&DockPosition::Left)
 6058            {
 6059                left_dock.resize_all_panels(Some(size), window, cx);
 6060            } else {
 6061                left_dock.resize_active_panel(Some(size), window, cx);
 6062            }
 6063        });
 6064    }
 6065
 6066    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6067        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6068        self.left_dock.read_with(cx, |left_dock, cx| {
 6069            let left_dock_size = left_dock
 6070                .active_panel_size(window, cx)
 6071                .unwrap_or(Pixels::ZERO);
 6072            if left_dock_size + size > self.bounds.right() {
 6073                size = self.bounds.right() - left_dock_size
 6074            }
 6075        });
 6076        self.right_dock.update(cx, |right_dock, cx| {
 6077            if WorkspaceSettings::get_global(cx)
 6078                .resize_all_panels_in_dock
 6079                .contains(&DockPosition::Right)
 6080            {
 6081                right_dock.resize_all_panels(Some(size), window, cx);
 6082            } else {
 6083                right_dock.resize_active_panel(Some(size), window, cx);
 6084            }
 6085        });
 6086    }
 6087
 6088    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6089        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6090        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6091            if WorkspaceSettings::get_global(cx)
 6092                .resize_all_panels_in_dock
 6093                .contains(&DockPosition::Bottom)
 6094            {
 6095                bottom_dock.resize_all_panels(Some(size), window, cx);
 6096            } else {
 6097                bottom_dock.resize_active_panel(Some(size), window, cx);
 6098            }
 6099        });
 6100    }
 6101
 6102    fn toggle_edit_predictions_all_files(
 6103        &mut self,
 6104        _: &ToggleEditPrediction,
 6105        _window: &mut Window,
 6106        cx: &mut Context<Self>,
 6107    ) {
 6108        let fs = self.project().read(cx).fs().clone();
 6109        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6110        update_settings_file(fs, cx, move |file, _| {
 6111            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6112        });
 6113    }
 6114}
 6115
 6116fn leader_border_for_pane(
 6117    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6118    pane: &Entity<Pane>,
 6119    _: &Window,
 6120    cx: &App,
 6121) -> Option<Div> {
 6122    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6123        if state.pane() == pane {
 6124            Some((*leader_id, state))
 6125        } else {
 6126            None
 6127        }
 6128    })?;
 6129
 6130    let mut leader_color = match leader_id {
 6131        CollaboratorId::PeerId(leader_peer_id) => {
 6132            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6133            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6134
 6135            cx.theme()
 6136                .players()
 6137                .color_for_participant(leader.participant_index.0)
 6138                .cursor
 6139        }
 6140        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6141    };
 6142    leader_color.fade_out(0.3);
 6143    Some(
 6144        div()
 6145            .absolute()
 6146            .size_full()
 6147            .left_0()
 6148            .top_0()
 6149            .border_2()
 6150            .border_color(leader_color),
 6151    )
 6152}
 6153
 6154fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 6155    ZED_WINDOW_POSITION
 6156        .zip(*ZED_WINDOW_SIZE)
 6157        .map(|(position, size)| Bounds {
 6158            origin: position,
 6159            size,
 6160        })
 6161}
 6162
 6163fn open_items(
 6164    serialized_workspace: Option<SerializedWorkspace>,
 6165    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 6166    window: &mut Window,
 6167    cx: &mut Context<Workspace>,
 6168) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 6169    let restored_items = serialized_workspace.map(|serialized_workspace| {
 6170        Workspace::load_workspace(
 6171            serialized_workspace,
 6172            project_paths_to_open
 6173                .iter()
 6174                .map(|(_, project_path)| project_path)
 6175                .cloned()
 6176                .collect(),
 6177            window,
 6178            cx,
 6179        )
 6180    });
 6181
 6182    cx.spawn_in(window, async move |workspace, cx| {
 6183        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 6184
 6185        if let Some(restored_items) = restored_items {
 6186            let restored_items = restored_items.await?;
 6187
 6188            let restored_project_paths = restored_items
 6189                .iter()
 6190                .filter_map(|item| {
 6191                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 6192                        .ok()
 6193                        .flatten()
 6194                })
 6195                .collect::<HashSet<_>>();
 6196
 6197            for restored_item in restored_items {
 6198                opened_items.push(restored_item.map(Ok));
 6199            }
 6200
 6201            project_paths_to_open
 6202                .iter_mut()
 6203                .for_each(|(_, project_path)| {
 6204                    if let Some(project_path_to_open) = project_path
 6205                        && restored_project_paths.contains(project_path_to_open)
 6206                    {
 6207                        *project_path = None;
 6208                    }
 6209                });
 6210        } else {
 6211            for _ in 0..project_paths_to_open.len() {
 6212                opened_items.push(None);
 6213            }
 6214        }
 6215        assert!(opened_items.len() == project_paths_to_open.len());
 6216
 6217        let tasks =
 6218            project_paths_to_open
 6219                .into_iter()
 6220                .enumerate()
 6221                .map(|(ix, (abs_path, project_path))| {
 6222                    let workspace = workspace.clone();
 6223                    cx.spawn(async move |cx| {
 6224                        let file_project_path = project_path?;
 6225                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6226                            workspace.project().update(cx, |project, cx| {
 6227                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6228                            })
 6229                        });
 6230
 6231                        // We only want to open file paths here. If one of the items
 6232                        // here is a directory, it was already opened further above
 6233                        // with a `find_or_create_worktree`.
 6234                        if let Ok(task) = abs_path_task
 6235                            && task.await.is_none_or(|p| p.is_file())
 6236                        {
 6237                            return Some((
 6238                                ix,
 6239                                workspace
 6240                                    .update_in(cx, |workspace, window, cx| {
 6241                                        workspace.open_path(
 6242                                            file_project_path,
 6243                                            None,
 6244                                            true,
 6245                                            window,
 6246                                            cx,
 6247                                        )
 6248                                    })
 6249                                    .log_err()?
 6250                                    .await,
 6251                            ));
 6252                        }
 6253                        None
 6254                    })
 6255                });
 6256
 6257        let tasks = tasks.collect::<Vec<_>>();
 6258
 6259        let tasks = futures::future::join_all(tasks);
 6260        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6261            opened_items[ix] = Some(path_open_result);
 6262        }
 6263
 6264        Ok(opened_items)
 6265    })
 6266}
 6267
 6268enum ActivateInDirectionTarget {
 6269    Pane(Entity<Pane>),
 6270    Dock(Entity<Dock>),
 6271}
 6272
 6273fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6274    workspace
 6275        .update(cx, |workspace, _, cx| {
 6276            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6277                struct DatabaseFailedNotification;
 6278
 6279                workspace.show_notification(
 6280                    NotificationId::unique::<DatabaseFailedNotification>(),
 6281                    cx,
 6282                    |cx| {
 6283                        cx.new(|cx| {
 6284                            MessageNotification::new("Failed to load the database file.", cx)
 6285                                .primary_message("File an Issue")
 6286                                .primary_icon(IconName::Plus)
 6287                                .primary_on_click(|window, cx| {
 6288                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6289                                })
 6290                        })
 6291                    },
 6292                );
 6293            }
 6294        })
 6295        .log_err();
 6296}
 6297
 6298fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6299    if val == 0 {
 6300        ThemeSettings::get_global(cx).ui_font_size(cx)
 6301    } else {
 6302        px(val as f32)
 6303    }
 6304}
 6305
 6306fn adjust_active_dock_size_by_px(
 6307    px: Pixels,
 6308    workspace: &mut Workspace,
 6309    window: &mut Window,
 6310    cx: &mut Context<Workspace>,
 6311) {
 6312    let Some(active_dock) = workspace
 6313        .all_docks()
 6314        .into_iter()
 6315        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6316    else {
 6317        return;
 6318    };
 6319    let dock = active_dock.read(cx);
 6320    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6321        return;
 6322    };
 6323    let dock_pos = dock.position();
 6324    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6325}
 6326
 6327fn adjust_open_docks_size_by_px(
 6328    px: Pixels,
 6329    workspace: &mut Workspace,
 6330    window: &mut Window,
 6331    cx: &mut Context<Workspace>,
 6332) {
 6333    let docks = workspace
 6334        .all_docks()
 6335        .into_iter()
 6336        .filter_map(|dock| {
 6337            if dock.read(cx).is_open() {
 6338                let dock = dock.read(cx);
 6339                let panel_size = dock.active_panel_size(window, cx)?;
 6340                let dock_pos = dock.position();
 6341                Some((panel_size, dock_pos, px))
 6342            } else {
 6343                None
 6344            }
 6345        })
 6346        .collect::<Vec<_>>();
 6347
 6348    docks
 6349        .into_iter()
 6350        .for_each(|(panel_size, dock_pos, offset)| {
 6351            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6352        });
 6353}
 6354
 6355impl Focusable for Workspace {
 6356    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6357        self.active_pane.focus_handle(cx)
 6358    }
 6359}
 6360
 6361#[derive(Clone)]
 6362struct DraggedDock(DockPosition);
 6363
 6364impl Render for DraggedDock {
 6365    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6366        gpui::Empty
 6367    }
 6368}
 6369
 6370impl Render for Workspace {
 6371    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6372        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 6373        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 6374            log::info!("Rendered first frame");
 6375        }
 6376        let mut context = KeyContext::new_with_defaults();
 6377        context.add("Workspace");
 6378        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6379        if let Some(status) = self
 6380            .debugger_provider
 6381            .as_ref()
 6382            .and_then(|provider| provider.active_thread_state(cx))
 6383        {
 6384            match status {
 6385                ThreadStatus::Running | ThreadStatus::Stepping => {
 6386                    context.add("debugger_running");
 6387                }
 6388                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6389                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6390            }
 6391        }
 6392
 6393        if self.left_dock.read(cx).is_open() {
 6394            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6395                context.set("left_dock", active_panel.panel_key());
 6396            }
 6397        }
 6398
 6399        if self.right_dock.read(cx).is_open() {
 6400            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6401                context.set("right_dock", active_panel.panel_key());
 6402            }
 6403        }
 6404
 6405        if self.bottom_dock.read(cx).is_open() {
 6406            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6407                context.set("bottom_dock", active_panel.panel_key());
 6408            }
 6409        }
 6410
 6411        let centered_layout = self.centered_layout
 6412            && self.center.panes().len() == 1
 6413            && self.active_item(cx).is_some();
 6414        let render_padding = |size| {
 6415            (size > 0.0).then(|| {
 6416                div()
 6417                    .h_full()
 6418                    .w(relative(size))
 6419                    .bg(cx.theme().colors().editor_background)
 6420                    .border_color(cx.theme().colors().pane_group_border)
 6421            })
 6422        };
 6423        let paddings = if centered_layout {
 6424            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6425            (
 6426                render_padding(Self::adjust_padding(settings.left_padding)),
 6427                render_padding(Self::adjust_padding(settings.right_padding)),
 6428            )
 6429        } else {
 6430            (None, None)
 6431        };
 6432        let ui_font = theme::setup_ui_font(window, cx);
 6433
 6434        let theme = cx.theme().clone();
 6435        let colors = theme.colors();
 6436        let notification_entities = self
 6437            .notifications
 6438            .iter()
 6439            .map(|(_, notification)| notification.entity_id())
 6440            .collect::<Vec<_>>();
 6441        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6442
 6443        client_side_decorations(
 6444            self.actions(div(), window, cx)
 6445                .key_context(context)
 6446                .relative()
 6447                .size_full()
 6448                .flex()
 6449                .flex_col()
 6450                .font(ui_font)
 6451                .gap_0()
 6452                .justify_start()
 6453                .items_start()
 6454                .text_color(colors.text)
 6455                .overflow_hidden()
 6456                .children(self.titlebar_item.clone())
 6457                .on_modifiers_changed(move |_, _, cx| {
 6458                    for &id in &notification_entities {
 6459                        cx.notify(id);
 6460                    }
 6461                })
 6462                .child(
 6463                    div()
 6464                        .size_full()
 6465                        .relative()
 6466                        .flex_1()
 6467                        .flex()
 6468                        .flex_col()
 6469                        .child(
 6470                            div()
 6471                                .id("workspace")
 6472                                .bg(colors.background)
 6473                                .relative()
 6474                                .flex_1()
 6475                                .w_full()
 6476                                .flex()
 6477                                .flex_col()
 6478                                .overflow_hidden()
 6479                                .border_t_1()
 6480                                .border_b_1()
 6481                                .border_color(colors.border)
 6482                                .child({
 6483                                    let this = cx.entity();
 6484                                    canvas(
 6485                                        move |bounds, window, cx| {
 6486                                            this.update(cx, |this, cx| {
 6487                                                let bounds_changed = this.bounds != bounds;
 6488                                                this.bounds = bounds;
 6489
 6490                                                if bounds_changed {
 6491                                                    this.left_dock.update(cx, |dock, cx| {
 6492                                                        dock.clamp_panel_size(
 6493                                                            bounds.size.width,
 6494                                                            window,
 6495                                                            cx,
 6496                                                        )
 6497                                                    });
 6498
 6499                                                    this.right_dock.update(cx, |dock, cx| {
 6500                                                        dock.clamp_panel_size(
 6501                                                            bounds.size.width,
 6502                                                            window,
 6503                                                            cx,
 6504                                                        )
 6505                                                    });
 6506
 6507                                                    this.bottom_dock.update(cx, |dock, cx| {
 6508                                                        dock.clamp_panel_size(
 6509                                                            bounds.size.height,
 6510                                                            window,
 6511                                                            cx,
 6512                                                        )
 6513                                                    });
 6514                                                }
 6515                                            })
 6516                                        },
 6517                                        |_, _, _, _| {},
 6518                                    )
 6519                                    .absolute()
 6520                                    .size_full()
 6521                                })
 6522                                .when(self.zoomed.is_none(), |this| {
 6523                                    this.on_drag_move(cx.listener(
 6524                                        move |workspace,
 6525                                              e: &DragMoveEvent<DraggedDock>,
 6526                                              window,
 6527                                              cx| {
 6528                                            if workspace.previous_dock_drag_coordinates
 6529                                                != Some(e.event.position)
 6530                                            {
 6531                                                workspace.previous_dock_drag_coordinates =
 6532                                                    Some(e.event.position);
 6533                                                match e.drag(cx).0 {
 6534                                                    DockPosition::Left => {
 6535                                                        workspace.resize_left_dock(
 6536                                                            e.event.position.x
 6537                                                                - workspace.bounds.left(),
 6538                                                            window,
 6539                                                            cx,
 6540                                                        );
 6541                                                    }
 6542                                                    DockPosition::Right => {
 6543                                                        workspace.resize_right_dock(
 6544                                                            workspace.bounds.right()
 6545                                                                - e.event.position.x,
 6546                                                            window,
 6547                                                            cx,
 6548                                                        );
 6549                                                    }
 6550                                                    DockPosition::Bottom => {
 6551                                                        workspace.resize_bottom_dock(
 6552                                                            workspace.bounds.bottom()
 6553                                                                - e.event.position.y,
 6554                                                            window,
 6555                                                            cx,
 6556                                                        );
 6557                                                    }
 6558                                                };
 6559                                                workspace.serialize_workspace(window, cx);
 6560                                            }
 6561                                        },
 6562                                    ))
 6563                                })
 6564                                .child({
 6565                                    match bottom_dock_layout {
 6566                                        BottomDockLayout::Full => div()
 6567                                            .flex()
 6568                                            .flex_col()
 6569                                            .h_full()
 6570                                            .child(
 6571                                                div()
 6572                                                    .flex()
 6573                                                    .flex_row()
 6574                                                    .flex_1()
 6575                                                    .overflow_hidden()
 6576                                                    .children(self.render_dock(
 6577                                                        DockPosition::Left,
 6578                                                        &self.left_dock,
 6579                                                        window,
 6580                                                        cx,
 6581                                                    ))
 6582                                                    .child(
 6583                                                        div()
 6584                                                            .flex()
 6585                                                            .flex_col()
 6586                                                            .flex_1()
 6587                                                            .overflow_hidden()
 6588                                                            .child(
 6589                                                                h_flex()
 6590                                                                    .flex_1()
 6591                                                                    .when_some(
 6592                                                                        paddings.0,
 6593                                                                        |this, p| {
 6594                                                                            this.child(
 6595                                                                                p.border_r_1(),
 6596                                                                            )
 6597                                                                        },
 6598                                                                    )
 6599                                                                    .child(self.center.render(
 6600                                                                        self.zoomed.as_ref(),
 6601                                                                        &PaneRenderContext {
 6602                                                                            follower_states:
 6603                                                                                &self.follower_states,
 6604                                                                            active_call: self.active_call(),
 6605                                                                            active_pane: &self.active_pane,
 6606                                                                            app_state: &self.app_state,
 6607                                                                            project: &self.project,
 6608                                                                            workspace: &self.weak_self,
 6609                                                                        },
 6610                                                                        window,
 6611                                                                        cx,
 6612                                                                    ))
 6613                                                                    .when_some(
 6614                                                                        paddings.1,
 6615                                                                        |this, p| {
 6616                                                                            this.child(
 6617                                                                                p.border_l_1(),
 6618                                                                            )
 6619                                                                        },
 6620                                                                    ),
 6621                                                            ),
 6622                                                    )
 6623                                                    .children(self.render_dock(
 6624                                                        DockPosition::Right,
 6625                                                        &self.right_dock,
 6626                                                        window,
 6627                                                        cx,
 6628                                                    )),
 6629                                            )
 6630                                            .child(div().w_full().children(self.render_dock(
 6631                                                DockPosition::Bottom,
 6632                                                &self.bottom_dock,
 6633                                                window,
 6634                                                cx
 6635                                            ))),
 6636
 6637                                        BottomDockLayout::LeftAligned => div()
 6638                                            .flex()
 6639                                            .flex_row()
 6640                                            .h_full()
 6641                                            .child(
 6642                                                div()
 6643                                                    .flex()
 6644                                                    .flex_col()
 6645                                                    .flex_1()
 6646                                                    .h_full()
 6647                                                    .child(
 6648                                                        div()
 6649                                                            .flex()
 6650                                                            .flex_row()
 6651                                                            .flex_1()
 6652                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 6653                                                            .child(
 6654                                                                div()
 6655                                                                    .flex()
 6656                                                                    .flex_col()
 6657                                                                    .flex_1()
 6658                                                                    .overflow_hidden()
 6659                                                                    .child(
 6660                                                                        h_flex()
 6661                                                                            .flex_1()
 6662                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6663                                                                            .child(self.center.render(
 6664                                                                                self.zoomed.as_ref(),
 6665                                                                                &PaneRenderContext {
 6666                                                                                    follower_states:
 6667                                                                                        &self.follower_states,
 6668                                                                                    active_call: self.active_call(),
 6669                                                                                    active_pane: &self.active_pane,
 6670                                                                                    app_state: &self.app_state,
 6671                                                                                    project: &self.project,
 6672                                                                                    workspace: &self.weak_self,
 6673                                                                                },
 6674                                                                                window,
 6675                                                                                cx,
 6676                                                                            ))
 6677                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6678                                                                    )
 6679                                                            )
 6680                                                    )
 6681                                                    .child(
 6682                                                        div()
 6683                                                            .w_full()
 6684                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6685                                                    ),
 6686                                            )
 6687                                            .children(self.render_dock(
 6688                                                DockPosition::Right,
 6689                                                &self.right_dock,
 6690                                                window,
 6691                                                cx,
 6692                                            )),
 6693
 6694                                        BottomDockLayout::RightAligned => div()
 6695                                            .flex()
 6696                                            .flex_row()
 6697                                            .h_full()
 6698                                            .children(self.render_dock(
 6699                                                DockPosition::Left,
 6700                                                &self.left_dock,
 6701                                                window,
 6702                                                cx,
 6703                                            ))
 6704                                            .child(
 6705                                                div()
 6706                                                    .flex()
 6707                                                    .flex_col()
 6708                                                    .flex_1()
 6709                                                    .h_full()
 6710                                                    .child(
 6711                                                        div()
 6712                                                            .flex()
 6713                                                            .flex_row()
 6714                                                            .flex_1()
 6715                                                            .child(
 6716                                                                div()
 6717                                                                    .flex()
 6718                                                                    .flex_col()
 6719                                                                    .flex_1()
 6720                                                                    .overflow_hidden()
 6721                                                                    .child(
 6722                                                                        h_flex()
 6723                                                                            .flex_1()
 6724                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6725                                                                            .child(self.center.render(
 6726                                                                                self.zoomed.as_ref(),
 6727                                                                                &PaneRenderContext {
 6728                                                                                    follower_states:
 6729                                                                                        &self.follower_states,
 6730                                                                                    active_call: self.active_call(),
 6731                                                                                    active_pane: &self.active_pane,
 6732                                                                                    app_state: &self.app_state,
 6733                                                                                    project: &self.project,
 6734                                                                                    workspace: &self.weak_self,
 6735                                                                                },
 6736                                                                                window,
 6737                                                                                cx,
 6738                                                                            ))
 6739                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6740                                                                    )
 6741                                                            )
 6742                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 6743                                                    )
 6744                                                    .child(
 6745                                                        div()
 6746                                                            .w_full()
 6747                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6748                                                    ),
 6749                                            ),
 6750
 6751                                        BottomDockLayout::Contained => div()
 6752                                            .flex()
 6753                                            .flex_row()
 6754                                            .h_full()
 6755                                            .children(self.render_dock(
 6756                                                DockPosition::Left,
 6757                                                &self.left_dock,
 6758                                                window,
 6759                                                cx,
 6760                                            ))
 6761                                            .child(
 6762                                                div()
 6763                                                    .flex()
 6764                                                    .flex_col()
 6765                                                    .flex_1()
 6766                                                    .overflow_hidden()
 6767                                                    .child(
 6768                                                        h_flex()
 6769                                                            .flex_1()
 6770                                                            .when_some(paddings.0, |this, p| {
 6771                                                                this.child(p.border_r_1())
 6772                                                            })
 6773                                                            .child(self.center.render(
 6774                                                                self.zoomed.as_ref(),
 6775                                                                &PaneRenderContext {
 6776                                                                    follower_states:
 6777                                                                        &self.follower_states,
 6778                                                                    active_call: self.active_call(),
 6779                                                                    active_pane: &self.active_pane,
 6780                                                                    app_state: &self.app_state,
 6781                                                                    project: &self.project,
 6782                                                                    workspace: &self.weak_self,
 6783                                                                },
 6784                                                                window,
 6785                                                                cx,
 6786                                                            ))
 6787                                                            .when_some(paddings.1, |this, p| {
 6788                                                                this.child(p.border_l_1())
 6789                                                            }),
 6790                                                    )
 6791                                                    .children(self.render_dock(
 6792                                                        DockPosition::Bottom,
 6793                                                        &self.bottom_dock,
 6794                                                        window,
 6795                                                        cx,
 6796                                                    )),
 6797                                            )
 6798                                            .children(self.render_dock(
 6799                                                DockPosition::Right,
 6800                                                &self.right_dock,
 6801                                                window,
 6802                                                cx,
 6803                                            )),
 6804                                    }
 6805                                })
 6806                                .children(self.zoomed.as_ref().and_then(|view| {
 6807                                    let zoomed_view = view.upgrade()?;
 6808                                    let div = div()
 6809                                        .occlude()
 6810                                        .absolute()
 6811                                        .overflow_hidden()
 6812                                        .border_color(colors.border)
 6813                                        .bg(colors.background)
 6814                                        .child(zoomed_view)
 6815                                        .inset_0()
 6816                                        .shadow_lg();
 6817
 6818                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 6819                                       return Some(div);
 6820                                    }
 6821
 6822                                    Some(match self.zoomed_position {
 6823                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 6824                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 6825                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 6826                                        None => {
 6827                                            div.top_2().bottom_2().left_2().right_2().border_1()
 6828                                        }
 6829                                    })
 6830                                }))
 6831                                .children(self.render_notifications(window, cx)),
 6832                        )
 6833                        .when(self.status_bar_visible(cx), |parent| {
 6834                            parent.child(self.status_bar.clone())
 6835                        })
 6836                        .child(self.modal_layer.clone())
 6837                        .child(self.toast_layer.clone()),
 6838                ),
 6839            window,
 6840            cx,
 6841        )
 6842    }
 6843}
 6844
 6845impl WorkspaceStore {
 6846    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 6847        Self {
 6848            workspaces: Default::default(),
 6849            _subscriptions: vec![
 6850                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 6851                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 6852            ],
 6853            client,
 6854        }
 6855    }
 6856
 6857    pub fn update_followers(
 6858        &self,
 6859        project_id: Option<u64>,
 6860        update: proto::update_followers::Variant,
 6861        cx: &App,
 6862    ) -> Option<()> {
 6863        let active_call = ActiveCall::try_global(cx)?;
 6864        let room_id = active_call.read(cx).room()?.read(cx).id();
 6865        self.client
 6866            .send(proto::UpdateFollowers {
 6867                room_id,
 6868                project_id,
 6869                variant: Some(update),
 6870            })
 6871            .log_err()
 6872    }
 6873
 6874    pub async fn handle_follow(
 6875        this: Entity<Self>,
 6876        envelope: TypedEnvelope<proto::Follow>,
 6877        mut cx: AsyncApp,
 6878    ) -> Result<proto::FollowResponse> {
 6879        this.update(&mut cx, |this, cx| {
 6880            let follower = Follower {
 6881                project_id: envelope.payload.project_id,
 6882                peer_id: envelope.original_sender_id()?,
 6883            };
 6884
 6885            let mut response = proto::FollowResponse::default();
 6886            this.workspaces.retain(|workspace| {
 6887                workspace
 6888                    .update(cx, |workspace, window, cx| {
 6889                        let handler_response =
 6890                            workspace.handle_follow(follower.project_id, window, cx);
 6891                        if let Some(active_view) = handler_response.active_view
 6892                            && workspace.project.read(cx).remote_id() == follower.project_id
 6893                        {
 6894                            response.active_view = Some(active_view)
 6895                        }
 6896                    })
 6897                    .is_ok()
 6898            });
 6899
 6900            Ok(response)
 6901        })?
 6902    }
 6903
 6904    async fn handle_update_followers(
 6905        this: Entity<Self>,
 6906        envelope: TypedEnvelope<proto::UpdateFollowers>,
 6907        mut cx: AsyncApp,
 6908    ) -> Result<()> {
 6909        let leader_id = envelope.original_sender_id()?;
 6910        let update = envelope.payload;
 6911
 6912        this.update(&mut cx, |this, cx| {
 6913            this.workspaces.retain(|workspace| {
 6914                workspace
 6915                    .update(cx, |workspace, window, cx| {
 6916                        let project_id = workspace.project.read(cx).remote_id();
 6917                        if update.project_id != project_id && update.project_id.is_some() {
 6918                            return;
 6919                        }
 6920                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 6921                    })
 6922                    .is_ok()
 6923            });
 6924            Ok(())
 6925        })?
 6926    }
 6927
 6928    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 6929        &self.workspaces
 6930    }
 6931}
 6932
 6933impl ViewId {
 6934    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 6935        Ok(Self {
 6936            creator: message
 6937                .creator
 6938                .map(CollaboratorId::PeerId)
 6939                .context("creator is missing")?,
 6940            id: message.id,
 6941        })
 6942    }
 6943
 6944    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 6945        if let CollaboratorId::PeerId(peer_id) = self.creator {
 6946            Some(proto::ViewId {
 6947                creator: Some(peer_id),
 6948                id: self.id,
 6949            })
 6950        } else {
 6951            None
 6952        }
 6953    }
 6954}
 6955
 6956impl FollowerState {
 6957    fn pane(&self) -> &Entity<Pane> {
 6958        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 6959    }
 6960}
 6961
 6962pub trait WorkspaceHandle {
 6963    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 6964}
 6965
 6966impl WorkspaceHandle for Entity<Workspace> {
 6967    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 6968        self.read(cx)
 6969            .worktrees(cx)
 6970            .flat_map(|worktree| {
 6971                let worktree_id = worktree.read(cx).id();
 6972                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 6973                    worktree_id,
 6974                    path: f.path.clone(),
 6975                })
 6976            })
 6977            .collect::<Vec<_>>()
 6978    }
 6979}
 6980
 6981pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 6982    DB.last_workspace().await.log_err().flatten()
 6983}
 6984
 6985pub fn last_session_workspace_locations(
 6986    last_session_id: &str,
 6987    last_session_window_stack: Option<Vec<WindowId>>,
 6988) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 6989    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 6990        .log_err()
 6991}
 6992
 6993actions!(
 6994    collab,
 6995    [
 6996        /// Opens the channel notes for the current call.
 6997        ///
 6998        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 6999        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7000        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7001        OpenChannelNotes,
 7002        /// Mutes your microphone.
 7003        Mute,
 7004        /// Deafens yourself (mute both microphone and speakers).
 7005        Deafen,
 7006        /// Leaves the current call.
 7007        LeaveCall,
 7008        /// Shares the current project with collaborators.
 7009        ShareProject,
 7010        /// Shares your screen with collaborators.
 7011        ScreenShare
 7012    ]
 7013);
 7014actions!(
 7015    zed,
 7016    [
 7017        /// Opens the Zed log file.
 7018        OpenLog,
 7019        /// Reveals the Zed log file in the system file manager.
 7020        RevealLogInFileManager
 7021    ]
 7022);
 7023
 7024async fn join_channel_internal(
 7025    channel_id: ChannelId,
 7026    app_state: &Arc<AppState>,
 7027    requesting_window: Option<WindowHandle<Workspace>>,
 7028    active_call: &Entity<ActiveCall>,
 7029    cx: &mut AsyncApp,
 7030) -> Result<bool> {
 7031    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7032        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7033            return (false, None);
 7034        };
 7035
 7036        let already_in_channel = room.channel_id() == Some(channel_id);
 7037        let should_prompt = room.is_sharing_project()
 7038            && !room.remote_participants().is_empty()
 7039            && !already_in_channel;
 7040        let open_room = if already_in_channel {
 7041            active_call.room().cloned()
 7042        } else {
 7043            None
 7044        };
 7045        (should_prompt, open_room)
 7046    })?;
 7047
 7048    if let Some(room) = open_room {
 7049        let task = room.update(cx, |room, cx| {
 7050            if let Some((project, host)) = room.most_active_project(cx) {
 7051                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7052            }
 7053
 7054            None
 7055        })?;
 7056        if let Some(task) = task {
 7057            task.await?;
 7058        }
 7059        return anyhow::Ok(true);
 7060    }
 7061
 7062    if should_prompt {
 7063        if let Some(workspace) = requesting_window {
 7064            let answer = workspace
 7065                .update(cx, |_, window, cx| {
 7066                    window.prompt(
 7067                        PromptLevel::Warning,
 7068                        "Do you want to switch channels?",
 7069                        Some("Leaving this call will unshare your current project."),
 7070                        &["Yes, Join Channel", "Cancel"],
 7071                        cx,
 7072                    )
 7073                })?
 7074                .await;
 7075
 7076            if answer == Ok(1) {
 7077                return Ok(false);
 7078            }
 7079        } else {
 7080            return Ok(false); // unreachable!() hopefully
 7081        }
 7082    }
 7083
 7084    let client = cx.update(|cx| active_call.read(cx).client())?;
 7085
 7086    let mut client_status = client.status();
 7087
 7088    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7089    'outer: loop {
 7090        let Some(status) = client_status.recv().await else {
 7091            anyhow::bail!("error connecting");
 7092        };
 7093
 7094        match status {
 7095            Status::Connecting
 7096            | Status::Authenticating
 7097            | Status::Authenticated
 7098            | Status::Reconnecting
 7099            | Status::Reauthenticating
 7100            | Status::Reauthenticated => continue,
 7101            Status::Connected { .. } => break 'outer,
 7102            Status::SignedOut | Status::AuthenticationError => {
 7103                return Err(ErrorCode::SignedOut.into());
 7104            }
 7105            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7106            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7107                return Err(ErrorCode::Disconnected.into());
 7108            }
 7109        }
 7110    }
 7111
 7112    let room = active_call
 7113        .update(cx, |active_call, cx| {
 7114            active_call.join_channel(channel_id, cx)
 7115        })?
 7116        .await?;
 7117
 7118    let Some(room) = room else {
 7119        return anyhow::Ok(true);
 7120    };
 7121
 7122    room.update(cx, |room, _| room.room_update_completed())?
 7123        .await;
 7124
 7125    let task = room.update(cx, |room, cx| {
 7126        if let Some((project, host)) = room.most_active_project(cx) {
 7127            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7128        }
 7129
 7130        // If you are the first to join a channel, see if you should share your project.
 7131        if room.remote_participants().is_empty()
 7132            && !room.local_participant_is_guest()
 7133            && let Some(workspace) = requesting_window
 7134        {
 7135            let project = workspace.update(cx, |workspace, _, cx| {
 7136                let project = workspace.project.read(cx);
 7137
 7138                if !CallSettings::get_global(cx).share_on_join {
 7139                    return None;
 7140                }
 7141
 7142                if (project.is_local() || project.is_via_remote_server())
 7143                    && project.visible_worktrees(cx).any(|tree| {
 7144                        tree.read(cx)
 7145                            .root_entry()
 7146                            .is_some_and(|entry| entry.is_dir())
 7147                    })
 7148                {
 7149                    Some(workspace.project.clone())
 7150                } else {
 7151                    None
 7152                }
 7153            });
 7154            if let Ok(Some(project)) = project {
 7155                return Some(cx.spawn(async move |room, cx| {
 7156                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7157                        .await?;
 7158                    Ok(())
 7159                }));
 7160            }
 7161        }
 7162
 7163        None
 7164    })?;
 7165    if let Some(task) = task {
 7166        task.await?;
 7167        return anyhow::Ok(true);
 7168    }
 7169    anyhow::Ok(false)
 7170}
 7171
 7172pub fn join_channel(
 7173    channel_id: ChannelId,
 7174    app_state: Arc<AppState>,
 7175    requesting_window: Option<WindowHandle<Workspace>>,
 7176    cx: &mut App,
 7177) -> Task<Result<()>> {
 7178    let active_call = ActiveCall::global(cx);
 7179    cx.spawn(async move |cx| {
 7180        let result = join_channel_internal(
 7181            channel_id,
 7182            &app_state,
 7183            requesting_window,
 7184            &active_call,
 7185             cx,
 7186        )
 7187            .await;
 7188
 7189        // join channel succeeded, and opened a window
 7190        if matches!(result, Ok(true)) {
 7191            return anyhow::Ok(());
 7192        }
 7193
 7194        // find an existing workspace to focus and show call controls
 7195        let mut active_window =
 7196            requesting_window.or_else(|| activate_any_workspace_window( cx));
 7197        if active_window.is_none() {
 7198            // no open workspaces, make one to show the error in (blergh)
 7199            let (window_handle, _) = cx
 7200                .update(|cx| {
 7201                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 7202                })?
 7203                .await?;
 7204
 7205            if result.is_ok() {
 7206                cx.update(|cx| {
 7207                    cx.dispatch_action(&OpenChannelNotes);
 7208                }).log_err();
 7209            }
 7210
 7211            active_window = Some(window_handle);
 7212        }
 7213
 7214        if let Err(err) = result {
 7215            log::error!("failed to join channel: {}", err);
 7216            if let Some(active_window) = active_window {
 7217                active_window
 7218                    .update(cx, |_, window, cx| {
 7219                        let detail: SharedString = match err.error_code() {
 7220                            ErrorCode::SignedOut => {
 7221                                "Please sign in to continue.".into()
 7222                            }
 7223                            ErrorCode::UpgradeRequired => {
 7224                                "Your are running an unsupported version of Zed. Please update to continue.".into()
 7225                            }
 7226                            ErrorCode::NoSuchChannel => {
 7227                                "No matching channel was found. Please check the link and try again.".into()
 7228                            }
 7229                            ErrorCode::Forbidden => {
 7230                                "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
 7231                            }
 7232                            ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
 7233                            _ => format!("{}\n\nPlease try again.", err).into(),
 7234                        };
 7235                        window.prompt(
 7236                            PromptLevel::Critical,
 7237                            "Failed to join channel",
 7238                            Some(&detail),
 7239                            &["Ok"],
 7240                        cx)
 7241                    })?
 7242                    .await
 7243                    .ok();
 7244            }
 7245        }
 7246
 7247        // return ok, we showed the error to the user.
 7248        anyhow::Ok(())
 7249    })
 7250}
 7251
 7252pub async fn get_any_active_workspace(
 7253    app_state: Arc<AppState>,
 7254    mut cx: AsyncApp,
 7255) -> anyhow::Result<WindowHandle<Workspace>> {
 7256    // find an existing workspace to focus and show call controls
 7257    let active_window = activate_any_workspace_window(&mut cx);
 7258    if active_window.is_none() {
 7259        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 7260            .await?;
 7261    }
 7262    activate_any_workspace_window(&mut cx).context("could not open zed")
 7263}
 7264
 7265fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7266    cx.update(|cx| {
 7267        if let Some(workspace_window) = cx
 7268            .active_window()
 7269            .and_then(|window| window.downcast::<Workspace>())
 7270        {
 7271            return Some(workspace_window);
 7272        }
 7273
 7274        for window in cx.windows() {
 7275            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7276                workspace_window
 7277                    .update(cx, |_, window, _| window.activate_window())
 7278                    .ok();
 7279                return Some(workspace_window);
 7280            }
 7281        }
 7282        None
 7283    })
 7284    .ok()
 7285    .flatten()
 7286}
 7287
 7288pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7289    cx.windows()
 7290        .into_iter()
 7291        .filter_map(|window| window.downcast::<Workspace>())
 7292        .filter(|workspace| {
 7293            workspace
 7294                .read(cx)
 7295                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7296        })
 7297        .collect()
 7298}
 7299
 7300#[derive(Default)]
 7301pub struct OpenOptions {
 7302    pub visible: Option<OpenVisible>,
 7303    pub focus: Option<bool>,
 7304    pub open_new_workspace: Option<bool>,
 7305    pub replace_window: Option<WindowHandle<Workspace>>,
 7306    pub env: Option<HashMap<String, String>>,
 7307}
 7308
 7309#[allow(clippy::type_complexity)]
 7310pub fn open_paths(
 7311    abs_paths: &[PathBuf],
 7312    app_state: Arc<AppState>,
 7313    open_options: OpenOptions,
 7314    cx: &mut App,
 7315) -> Task<
 7316    anyhow::Result<(
 7317        WindowHandle<Workspace>,
 7318        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7319    )>,
 7320> {
 7321    let abs_paths = abs_paths.to_vec();
 7322    let mut existing = None;
 7323    let mut best_match = None;
 7324    let mut open_visible = OpenVisible::All;
 7325
 7326    cx.spawn(async move |cx| {
 7327        if open_options.open_new_workspace != Some(true) {
 7328            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7329            let all_metadatas = futures::future::join_all(all_paths)
 7330                .await
 7331                .into_iter()
 7332                .filter_map(|result| result.ok().flatten())
 7333                .collect::<Vec<_>>();
 7334
 7335            cx.update(|cx| {
 7336                for window in local_workspace_windows(cx) {
 7337                    if let Ok(workspace) = window.read(cx) {
 7338                        let m = workspace.project.read(cx).visibility_for_paths(
 7339                            &abs_paths,
 7340                            &all_metadatas,
 7341                            open_options.open_new_workspace == None,
 7342                            cx,
 7343                        );
 7344                        if m > best_match {
 7345                            existing = Some(window);
 7346                            best_match = m;
 7347                        } else if best_match.is_none()
 7348                            && open_options.open_new_workspace == Some(false)
 7349                        {
 7350                            existing = Some(window)
 7351                        }
 7352                    }
 7353                }
 7354            })?;
 7355
 7356            if open_options.open_new_workspace.is_none()
 7357                && existing.is_none()
 7358                && all_metadatas.iter().all(|file| !file.is_dir)
 7359            {
 7360                cx.update(|cx| {
 7361                    if let Some(window) = cx
 7362                        .active_window()
 7363                        .and_then(|window| window.downcast::<Workspace>())
 7364                        && let Ok(workspace) = window.read(cx)
 7365                    {
 7366                        let project = workspace.project().read(cx);
 7367                        if project.is_local() && !project.is_via_collab() {
 7368                            existing = Some(window);
 7369                            open_visible = OpenVisible::None;
 7370                            return;
 7371                        }
 7372                    }
 7373                    for window in local_workspace_windows(cx) {
 7374                        if let Ok(workspace) = window.read(cx) {
 7375                            let project = workspace.project().read(cx);
 7376                            if project.is_via_collab() {
 7377                                continue;
 7378                            }
 7379                            existing = Some(window);
 7380                            open_visible = OpenVisible::None;
 7381                            break;
 7382                        }
 7383                    }
 7384                })?;
 7385            }
 7386        }
 7387
 7388        if let Some(existing) = existing {
 7389            let open_task = existing
 7390                .update(cx, |workspace, window, cx| {
 7391                    window.activate_window();
 7392                    workspace.open_paths(
 7393                        abs_paths,
 7394                        OpenOptions {
 7395                            visible: Some(open_visible),
 7396                            ..Default::default()
 7397                        },
 7398                        None,
 7399                        window,
 7400                        cx,
 7401                    )
 7402                })?
 7403                .await;
 7404
 7405            _ = existing.update(cx, |workspace, _, cx| {
 7406                for item in open_task.iter().flatten() {
 7407                    if let Err(e) = item {
 7408                        workspace.show_error(&e, cx);
 7409                    }
 7410                }
 7411            });
 7412
 7413            Ok((existing, open_task))
 7414        } else {
 7415            cx.update(move |cx| {
 7416                Workspace::new_local(
 7417                    abs_paths,
 7418                    app_state.clone(),
 7419                    open_options.replace_window,
 7420                    open_options.env,
 7421                    cx,
 7422                )
 7423            })?
 7424            .await
 7425        }
 7426    })
 7427}
 7428
 7429pub fn open_new(
 7430    open_options: OpenOptions,
 7431    app_state: Arc<AppState>,
 7432    cx: &mut App,
 7433    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7434) -> Task<anyhow::Result<()>> {
 7435    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7436    cx.spawn(async move |cx| {
 7437        let (workspace, opened_paths) = task.await?;
 7438        workspace.update(cx, |workspace, window, cx| {
 7439            if opened_paths.is_empty() {
 7440                init(workspace, window, cx)
 7441            }
 7442        })?;
 7443        Ok(())
 7444    })
 7445}
 7446
 7447pub fn create_and_open_local_file(
 7448    path: &'static Path,
 7449    window: &mut Window,
 7450    cx: &mut Context<Workspace>,
 7451    default_content: impl 'static + Send + FnOnce() -> Rope,
 7452) -> Task<Result<Box<dyn ItemHandle>>> {
 7453    cx.spawn_in(window, async move |workspace, cx| {
 7454        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7455        if !fs.is_file(path).await {
 7456            fs.create_file(path, Default::default()).await?;
 7457            fs.save(path, &default_content(), Default::default())
 7458                .await?;
 7459        }
 7460
 7461        let mut items = workspace
 7462            .update_in(cx, |workspace, window, cx| {
 7463                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7464                    workspace.open_paths(
 7465                        vec![path.to_path_buf()],
 7466                        OpenOptions {
 7467                            visible: Some(OpenVisible::None),
 7468                            ..Default::default()
 7469                        },
 7470                        None,
 7471                        window,
 7472                        cx,
 7473                    )
 7474                })
 7475            })?
 7476            .await?
 7477            .await;
 7478
 7479        let item = items.pop().flatten();
 7480        item.with_context(|| format!("path {path:?} is not a file"))?
 7481    })
 7482}
 7483
 7484pub fn open_remote_project_with_new_connection(
 7485    window: WindowHandle<Workspace>,
 7486    remote_connection: Arc<dyn RemoteConnection>,
 7487    cancel_rx: oneshot::Receiver<()>,
 7488    delegate: Arc<dyn RemoteClientDelegate>,
 7489    app_state: Arc<AppState>,
 7490    paths: Vec<PathBuf>,
 7491    cx: &mut App,
 7492) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7493    cx.spawn(async move |cx| {
 7494        let (workspace_id, serialized_workspace) =
 7495            serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 7496                .await?;
 7497
 7498        let session = match cx
 7499            .update(|cx| {
 7500                remote::RemoteClient::new(
 7501                    ConnectionIdentifier::Workspace(workspace_id.0),
 7502                    remote_connection,
 7503                    cancel_rx,
 7504                    delegate,
 7505                    cx,
 7506                )
 7507            })?
 7508            .await?
 7509        {
 7510            Some(result) => result,
 7511            None => return Ok(Vec::new()),
 7512        };
 7513
 7514        let project = cx.update(|cx| {
 7515            project::Project::remote(
 7516                session,
 7517                app_state.client.clone(),
 7518                app_state.node_runtime.clone(),
 7519                app_state.user_store.clone(),
 7520                app_state.languages.clone(),
 7521                app_state.fs.clone(),
 7522                cx,
 7523            )
 7524        })?;
 7525
 7526        open_remote_project_inner(
 7527            project,
 7528            paths,
 7529            workspace_id,
 7530            serialized_workspace,
 7531            app_state,
 7532            window,
 7533            cx,
 7534        )
 7535        .await
 7536    })
 7537}
 7538
 7539pub fn open_remote_project_with_existing_connection(
 7540    connection_options: RemoteConnectionOptions,
 7541    project: Entity<Project>,
 7542    paths: Vec<PathBuf>,
 7543    app_state: Arc<AppState>,
 7544    window: WindowHandle<Workspace>,
 7545    cx: &mut AsyncApp,
 7546) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7547    cx.spawn(async move |cx| {
 7548        let (workspace_id, serialized_workspace) =
 7549            serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7550
 7551        open_remote_project_inner(
 7552            project,
 7553            paths,
 7554            workspace_id,
 7555            serialized_workspace,
 7556            app_state,
 7557            window,
 7558            cx,
 7559        )
 7560        .await
 7561    })
 7562}
 7563
 7564async fn open_remote_project_inner(
 7565    project: Entity<Project>,
 7566    paths: Vec<PathBuf>,
 7567    workspace_id: WorkspaceId,
 7568    serialized_workspace: Option<SerializedWorkspace>,
 7569    app_state: Arc<AppState>,
 7570    window: WindowHandle<Workspace>,
 7571    cx: &mut AsyncApp,
 7572) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 7573    let toolchains = DB.toolchains(workspace_id).await?;
 7574    for (toolchain, worktree_id, path) in toolchains {
 7575        project
 7576            .update(cx, |this, cx| {
 7577                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7578            })?
 7579            .await;
 7580    }
 7581    let mut project_paths_to_open = vec![];
 7582    let mut project_path_errors = vec![];
 7583
 7584    for path in paths {
 7585        let result = cx
 7586            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7587            .await;
 7588        match result {
 7589            Ok((_, project_path)) => {
 7590                project_paths_to_open.push((path.clone(), Some(project_path)));
 7591            }
 7592            Err(error) => {
 7593                project_path_errors.push(error);
 7594            }
 7595        };
 7596    }
 7597
 7598    if project_paths_to_open.is_empty() {
 7599        return Err(project_path_errors.pop().context("no paths given")?);
 7600    }
 7601
 7602    if let Some(detach_session_task) = window
 7603        .update(cx, |_workspace, window, cx| {
 7604            cx.spawn_in(window, async move |this, cx| {
 7605                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 7606            })
 7607        })
 7608        .ok()
 7609    {
 7610        detach_session_task.await.ok();
 7611    }
 7612
 7613    cx.update_window(window.into(), |_, window, cx| {
 7614        window.replace_root(cx, |window, cx| {
 7615            telemetry::event!("SSH Project Opened");
 7616
 7617            let mut workspace =
 7618                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7619            workspace.update_history(cx);
 7620
 7621            if let Some(ref serialized) = serialized_workspace {
 7622                workspace.centered_layout = serialized.centered_layout;
 7623            }
 7624
 7625            workspace
 7626        });
 7627    })?;
 7628
 7629    let items = window
 7630        .update(cx, |_, window, cx| {
 7631            window.activate_window();
 7632            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7633        })?
 7634        .await?;
 7635
 7636    window.update(cx, |workspace, _, cx| {
 7637        for error in project_path_errors {
 7638            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7639                if let Some(path) = error.error_tag("path") {
 7640                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7641                }
 7642            } else {
 7643                workspace.show_error(&error, cx)
 7644            }
 7645        }
 7646    })?;
 7647
 7648    Ok(items.into_iter().map(|item| item?.ok()).collect())
 7649}
 7650
 7651fn serialize_remote_project(
 7652    connection_options: RemoteConnectionOptions,
 7653    paths: Vec<PathBuf>,
 7654    cx: &AsyncApp,
 7655) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7656    cx.background_spawn(async move {
 7657        let remote_connection_id = persistence::DB
 7658            .get_or_create_remote_connection(connection_options)
 7659            .await?;
 7660
 7661        let serialized_workspace =
 7662            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 7663
 7664        let workspace_id = if let Some(workspace_id) =
 7665            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7666        {
 7667            workspace_id
 7668        } else {
 7669            persistence::DB.next_id().await?
 7670        };
 7671
 7672        Ok((workspace_id, serialized_workspace))
 7673    })
 7674}
 7675
 7676pub fn join_in_room_project(
 7677    project_id: u64,
 7678    follow_user_id: u64,
 7679    app_state: Arc<AppState>,
 7680    cx: &mut App,
 7681) -> Task<Result<()>> {
 7682    let windows = cx.windows();
 7683    cx.spawn(async move |cx| {
 7684        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7685            window_handle
 7686                .downcast::<Workspace>()
 7687                .and_then(|window_handle| {
 7688                    window_handle
 7689                        .update(cx, |workspace, _window, cx| {
 7690                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7691                                Some(window_handle)
 7692                            } else {
 7693                                None
 7694                            }
 7695                        })
 7696                        .unwrap_or(None)
 7697                })
 7698        });
 7699
 7700        let workspace = if let Some(existing_workspace) = existing_workspace {
 7701            existing_workspace
 7702        } else {
 7703            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7704            let room = active_call
 7705                .read_with(cx, |call, _| call.room().cloned())?
 7706                .context("not in a call")?;
 7707            let project = room
 7708                .update(cx, |room, cx| {
 7709                    room.join_project(
 7710                        project_id,
 7711                        app_state.languages.clone(),
 7712                        app_state.fs.clone(),
 7713                        cx,
 7714                    )
 7715                })?
 7716                .await?;
 7717
 7718            let window_bounds_override = window_bounds_env_override();
 7719            cx.update(|cx| {
 7720                let mut options = (app_state.build_window_options)(None, cx);
 7721                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7722                cx.open_window(options, |window, cx| {
 7723                    cx.new(|cx| {
 7724                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7725                    })
 7726                })
 7727            })??
 7728        };
 7729
 7730        workspace.update(cx, |workspace, window, cx| {
 7731            cx.activate(true);
 7732            window.activate_window();
 7733
 7734            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7735                let follow_peer_id = room
 7736                    .read(cx)
 7737                    .remote_participants()
 7738                    .iter()
 7739                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7740                    .map(|(_, p)| p.peer_id)
 7741                    .or_else(|| {
 7742                        // If we couldn't follow the given user, follow the host instead.
 7743                        let collaborator = workspace
 7744                            .project()
 7745                            .read(cx)
 7746                            .collaborators()
 7747                            .values()
 7748                            .find(|collaborator| collaborator.is_host)?;
 7749                        Some(collaborator.peer_id)
 7750                    });
 7751
 7752                if let Some(follow_peer_id) = follow_peer_id {
 7753                    workspace.follow(follow_peer_id, window, cx);
 7754                }
 7755            }
 7756        })?;
 7757
 7758        anyhow::Ok(())
 7759    })
 7760}
 7761
 7762pub fn reload(cx: &mut App) {
 7763    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7764    let mut workspace_windows = cx
 7765        .windows()
 7766        .into_iter()
 7767        .filter_map(|window| window.downcast::<Workspace>())
 7768        .collect::<Vec<_>>();
 7769
 7770    // If multiple windows have unsaved changes, and need a save prompt,
 7771    // prompt in the active window before switching to a different window.
 7772    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7773
 7774    let mut prompt = None;
 7775    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7776        prompt = window
 7777            .update(cx, |_, window, cx| {
 7778                window.prompt(
 7779                    PromptLevel::Info,
 7780                    "Are you sure you want to restart?",
 7781                    None,
 7782                    &["Restart", "Cancel"],
 7783                    cx,
 7784                )
 7785            })
 7786            .ok();
 7787    }
 7788
 7789    cx.spawn(async move |cx| {
 7790        if let Some(prompt) = prompt {
 7791            let answer = prompt.await?;
 7792            if answer != 0 {
 7793                return Ok(());
 7794            }
 7795        }
 7796
 7797        // If the user cancels any save prompt, then keep the app open.
 7798        for window in workspace_windows {
 7799            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7800                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7801            }) && !should_close.await?
 7802            {
 7803                return Ok(());
 7804            }
 7805        }
 7806        cx.update(|cx| cx.restart())
 7807    })
 7808    .detach_and_log_err(cx);
 7809}
 7810
 7811fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7812    let mut parts = value.split(',');
 7813    let x: usize = parts.next()?.parse().ok()?;
 7814    let y: usize = parts.next()?.parse().ok()?;
 7815    Some(point(px(x as f32), px(y as f32)))
 7816}
 7817
 7818fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7819    let mut parts = value.split(',');
 7820    let width: usize = parts.next()?.parse().ok()?;
 7821    let height: usize = parts.next()?.parse().ok()?;
 7822    Some(size(px(width as f32), px(height as f32)))
 7823}
 7824
 7825/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7826pub fn client_side_decorations(
 7827    element: impl IntoElement,
 7828    window: &mut Window,
 7829    cx: &mut App,
 7830) -> Stateful<Div> {
 7831    const BORDER_SIZE: Pixels = px(1.0);
 7832    let decorations = window.window_decorations();
 7833
 7834    match decorations {
 7835        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7836        Decorations::Server => window.set_client_inset(px(0.0)),
 7837    }
 7838
 7839    struct GlobalResizeEdge(ResizeEdge);
 7840    impl Global for GlobalResizeEdge {}
 7841
 7842    div()
 7843        .id("window-backdrop")
 7844        .bg(transparent_black())
 7845        .map(|div| match decorations {
 7846            Decorations::Server => div,
 7847            Decorations::Client { tiling, .. } => div
 7848                .when(!(tiling.top || tiling.right), |div| {
 7849                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7850                })
 7851                .when(!(tiling.top || tiling.left), |div| {
 7852                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7853                })
 7854                .when(!(tiling.bottom || tiling.right), |div| {
 7855                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7856                })
 7857                .when(!(tiling.bottom || tiling.left), |div| {
 7858                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7859                })
 7860                .when(!tiling.top, |div| {
 7861                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7862                })
 7863                .when(!tiling.bottom, |div| {
 7864                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7865                })
 7866                .when(!tiling.left, |div| {
 7867                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7868                })
 7869                .when(!tiling.right, |div| {
 7870                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7871                })
 7872                .on_mouse_move(move |e, window, cx| {
 7873                    let size = window.window_bounds().get_bounds().size;
 7874                    let pos = e.position;
 7875
 7876                    let new_edge =
 7877                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 7878
 7879                    let edge = cx.try_global::<GlobalResizeEdge>();
 7880                    if new_edge != edge.map(|edge| edge.0) {
 7881                        window
 7882                            .window_handle()
 7883                            .update(cx, |workspace, _, cx| {
 7884                                cx.notify(workspace.entity_id());
 7885                            })
 7886                            .ok();
 7887                    }
 7888                })
 7889                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 7890                    let size = window.window_bounds().get_bounds().size;
 7891                    let pos = e.position;
 7892
 7893                    let edge = match resize_edge(
 7894                        pos,
 7895                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 7896                        size,
 7897                        tiling,
 7898                    ) {
 7899                        Some(value) => value,
 7900                        None => return,
 7901                    };
 7902
 7903                    window.start_window_resize(edge);
 7904                }),
 7905        })
 7906        .size_full()
 7907        .child(
 7908            div()
 7909                .cursor(CursorStyle::Arrow)
 7910                .map(|div| match decorations {
 7911                    Decorations::Server => div,
 7912                    Decorations::Client { tiling } => div
 7913                        .border_color(cx.theme().colors().border)
 7914                        .when(!(tiling.top || tiling.right), |div| {
 7915                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7916                        })
 7917                        .when(!(tiling.top || tiling.left), |div| {
 7918                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7919                        })
 7920                        .when(!(tiling.bottom || tiling.right), |div| {
 7921                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7922                        })
 7923                        .when(!(tiling.bottom || tiling.left), |div| {
 7924                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7925                        })
 7926                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 7927                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 7928                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 7929                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 7930                        .when(!tiling.is_tiled(), |div| {
 7931                            div.shadow(vec![gpui::BoxShadow {
 7932                                color: Hsla {
 7933                                    h: 0.,
 7934                                    s: 0.,
 7935                                    l: 0.,
 7936                                    a: 0.4,
 7937                                },
 7938                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 7939                                spread_radius: px(0.),
 7940                                offset: point(px(0.0), px(0.0)),
 7941                            }])
 7942                        }),
 7943                })
 7944                .on_mouse_move(|_e, _, cx| {
 7945                    cx.stop_propagation();
 7946                })
 7947                .size_full()
 7948                .child(element),
 7949        )
 7950        .map(|div| match decorations {
 7951            Decorations::Server => div,
 7952            Decorations::Client { tiling, .. } => div.child(
 7953                canvas(
 7954                    |_bounds, window, _| {
 7955                        window.insert_hitbox(
 7956                            Bounds::new(
 7957                                point(px(0.0), px(0.0)),
 7958                                window.window_bounds().get_bounds().size,
 7959                            ),
 7960                            HitboxBehavior::Normal,
 7961                        )
 7962                    },
 7963                    move |_bounds, hitbox, window, cx| {
 7964                        let mouse = window.mouse_position();
 7965                        let size = window.window_bounds().get_bounds().size;
 7966                        let Some(edge) =
 7967                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 7968                        else {
 7969                            return;
 7970                        };
 7971                        cx.set_global(GlobalResizeEdge(edge));
 7972                        window.set_cursor_style(
 7973                            match edge {
 7974                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 7975                                ResizeEdge::Left | ResizeEdge::Right => {
 7976                                    CursorStyle::ResizeLeftRight
 7977                                }
 7978                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 7979                                    CursorStyle::ResizeUpLeftDownRight
 7980                                }
 7981                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 7982                                    CursorStyle::ResizeUpRightDownLeft
 7983                                }
 7984                            },
 7985                            &hitbox,
 7986                        );
 7987                    },
 7988                )
 7989                .size_full()
 7990                .absolute(),
 7991            ),
 7992        })
 7993}
 7994
 7995fn resize_edge(
 7996    pos: Point<Pixels>,
 7997    shadow_size: Pixels,
 7998    window_size: Size<Pixels>,
 7999    tiling: Tiling,
 8000) -> Option<ResizeEdge> {
 8001    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8002    if bounds.contains(&pos) {
 8003        return None;
 8004    }
 8005
 8006    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8007    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8008    if !tiling.top && top_left_bounds.contains(&pos) {
 8009        return Some(ResizeEdge::TopLeft);
 8010    }
 8011
 8012    let top_right_bounds = Bounds::new(
 8013        Point::new(window_size.width - corner_size.width, px(0.)),
 8014        corner_size,
 8015    );
 8016    if !tiling.top && top_right_bounds.contains(&pos) {
 8017        return Some(ResizeEdge::TopRight);
 8018    }
 8019
 8020    let bottom_left_bounds = Bounds::new(
 8021        Point::new(px(0.), window_size.height - corner_size.height),
 8022        corner_size,
 8023    );
 8024    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8025        return Some(ResizeEdge::BottomLeft);
 8026    }
 8027
 8028    let bottom_right_bounds = Bounds::new(
 8029        Point::new(
 8030            window_size.width - corner_size.width,
 8031            window_size.height - corner_size.height,
 8032        ),
 8033        corner_size,
 8034    );
 8035    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8036        return Some(ResizeEdge::BottomRight);
 8037    }
 8038
 8039    if !tiling.top && pos.y < shadow_size {
 8040        Some(ResizeEdge::Top)
 8041    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8042        Some(ResizeEdge::Bottom)
 8043    } else if !tiling.left && pos.x < shadow_size {
 8044        Some(ResizeEdge::Left)
 8045    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8046        Some(ResizeEdge::Right)
 8047    } else {
 8048        None
 8049    }
 8050}
 8051
 8052fn join_pane_into_active(
 8053    active_pane: &Entity<Pane>,
 8054    pane: &Entity<Pane>,
 8055    window: &mut Window,
 8056    cx: &mut App,
 8057) {
 8058    if pane == active_pane {
 8059    } else if pane.read(cx).items_len() == 0 {
 8060        pane.update(cx, |_, cx| {
 8061            cx.emit(pane::Event::Remove {
 8062                focus_on_pane: None,
 8063            });
 8064        })
 8065    } else {
 8066        move_all_items(pane, active_pane, window, cx);
 8067    }
 8068}
 8069
 8070fn move_all_items(
 8071    from_pane: &Entity<Pane>,
 8072    to_pane: &Entity<Pane>,
 8073    window: &mut Window,
 8074    cx: &mut App,
 8075) {
 8076    let destination_is_different = from_pane != to_pane;
 8077    let mut moved_items = 0;
 8078    for (item_ix, item_handle) in from_pane
 8079        .read(cx)
 8080        .items()
 8081        .enumerate()
 8082        .map(|(ix, item)| (ix, item.clone()))
 8083        .collect::<Vec<_>>()
 8084    {
 8085        let ix = item_ix - moved_items;
 8086        if destination_is_different {
 8087            // Close item from previous pane
 8088            from_pane.update(cx, |source, cx| {
 8089                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8090            });
 8091            moved_items += 1;
 8092        }
 8093
 8094        // This automatically removes duplicate items in the pane
 8095        to_pane.update(cx, |destination, cx| {
 8096            destination.add_item(item_handle, true, true, None, window, cx);
 8097            window.focus(&destination.focus_handle(cx))
 8098        });
 8099    }
 8100}
 8101
 8102pub fn move_item(
 8103    source: &Entity<Pane>,
 8104    destination: &Entity<Pane>,
 8105    item_id_to_move: EntityId,
 8106    destination_index: usize,
 8107    activate: bool,
 8108    window: &mut Window,
 8109    cx: &mut App,
 8110) {
 8111    let Some((item_ix, item_handle)) = source
 8112        .read(cx)
 8113        .items()
 8114        .enumerate()
 8115        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8116        .map(|(ix, item)| (ix, item.clone()))
 8117    else {
 8118        // Tab was closed during drag
 8119        return;
 8120    };
 8121
 8122    if source != destination {
 8123        // Close item from previous pane
 8124        source.update(cx, |source, cx| {
 8125            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8126        });
 8127    }
 8128
 8129    // This automatically removes duplicate items in the pane
 8130    destination.update(cx, |destination, cx| {
 8131        destination.add_item_inner(
 8132            item_handle,
 8133            activate,
 8134            activate,
 8135            activate,
 8136            Some(destination_index),
 8137            window,
 8138            cx,
 8139        );
 8140        if activate {
 8141            window.focus(&destination.focus_handle(cx))
 8142        }
 8143    });
 8144}
 8145
 8146pub fn move_active_item(
 8147    source: &Entity<Pane>,
 8148    destination: &Entity<Pane>,
 8149    focus_destination: bool,
 8150    close_if_empty: bool,
 8151    window: &mut Window,
 8152    cx: &mut App,
 8153) {
 8154    if source == destination {
 8155        return;
 8156    }
 8157    let Some(active_item) = source.read(cx).active_item() else {
 8158        return;
 8159    };
 8160    source.update(cx, |source_pane, cx| {
 8161        let item_id = active_item.item_id();
 8162        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8163        destination.update(cx, |target_pane, cx| {
 8164            target_pane.add_item(
 8165                active_item,
 8166                focus_destination,
 8167                focus_destination,
 8168                Some(target_pane.items_len()),
 8169                window,
 8170                cx,
 8171            );
 8172        });
 8173    });
 8174}
 8175
 8176pub fn clone_active_item(
 8177    workspace_id: Option<WorkspaceId>,
 8178    source: &Entity<Pane>,
 8179    destination: &Entity<Pane>,
 8180    focus_destination: bool,
 8181    window: &mut Window,
 8182    cx: &mut App,
 8183) {
 8184    if source == destination {
 8185        return;
 8186    }
 8187    let Some(active_item) = source.read(cx).active_item() else {
 8188        return;
 8189    };
 8190    let destination = destination.downgrade();
 8191    let task = active_item.clone_on_split(workspace_id, window, cx);
 8192    window
 8193        .spawn(cx, async move |cx| {
 8194            let Some(clone) = task.await else {
 8195                return;
 8196            };
 8197            destination
 8198                .update_in(cx, |target_pane, window, cx| {
 8199                    target_pane.add_item(
 8200                        clone,
 8201                        focus_destination,
 8202                        focus_destination,
 8203                        Some(target_pane.items_len()),
 8204                        window,
 8205                        cx,
 8206                    );
 8207                })
 8208                .log_err();
 8209        })
 8210        .detach();
 8211}
 8212
 8213#[derive(Debug)]
 8214pub struct WorkspacePosition {
 8215    pub window_bounds: Option<WindowBounds>,
 8216    pub display: Option<Uuid>,
 8217    pub centered_layout: bool,
 8218}
 8219
 8220pub fn remote_workspace_position_from_db(
 8221    connection_options: RemoteConnectionOptions,
 8222    paths_to_open: &[PathBuf],
 8223    cx: &App,
 8224) -> Task<Result<WorkspacePosition>> {
 8225    let paths = paths_to_open.to_vec();
 8226
 8227    cx.background_spawn(async move {
 8228        let remote_connection_id = persistence::DB
 8229            .get_or_create_remote_connection(connection_options)
 8230            .await
 8231            .context("fetching serialized ssh project")?;
 8232        let serialized_workspace =
 8233            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8234
 8235        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8236            (Some(WindowBounds::Windowed(bounds)), None)
 8237        } else {
 8238            let restorable_bounds = serialized_workspace
 8239                .as_ref()
 8240                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8241                .or_else(|| {
 8242                    let (display, window_bounds) = DB.last_window().log_err()?;
 8243                    Some((display?, window_bounds?))
 8244                });
 8245
 8246            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8247                (Some(serialized_status.0), Some(serialized_display))
 8248            } else {
 8249                (None, None)
 8250            }
 8251        };
 8252
 8253        let centered_layout = serialized_workspace
 8254            .as_ref()
 8255            .map(|w| w.centered_layout)
 8256            .unwrap_or(false);
 8257
 8258        Ok(WorkspacePosition {
 8259            window_bounds,
 8260            display,
 8261            centered_layout,
 8262        })
 8263    })
 8264}
 8265
 8266pub fn with_active_or_new_workspace(
 8267    cx: &mut App,
 8268    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8269) {
 8270    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8271        Some(workspace) => {
 8272            cx.defer(move |cx| {
 8273                workspace
 8274                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8275                    .log_err();
 8276            });
 8277        }
 8278        None => {
 8279            let app_state = AppState::global(cx);
 8280            if let Some(app_state) = app_state.upgrade() {
 8281                open_new(
 8282                    OpenOptions::default(),
 8283                    app_state,
 8284                    cx,
 8285                    move |workspace, window, cx| f(workspace, window, cx),
 8286                )
 8287                .detach_and_log_err(cx);
 8288            }
 8289        }
 8290    }
 8291}
 8292
 8293#[cfg(test)]
 8294mod tests {
 8295    use std::{cell::RefCell, rc::Rc};
 8296
 8297    use super::*;
 8298    use crate::{
 8299        dock::{PanelEvent, test::TestPanel},
 8300        item::{
 8301            ItemBufferKind, ItemEvent,
 8302            test::{TestItem, TestProjectItem},
 8303        },
 8304    };
 8305    use fs::FakeFs;
 8306    use gpui::{
 8307        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8308        UpdateGlobal, VisualTestContext, px,
 8309    };
 8310    use project::{Project, ProjectEntryId};
 8311    use serde_json::json;
 8312    use settings::SettingsStore;
 8313    use util::rel_path::rel_path;
 8314
 8315    #[gpui::test]
 8316    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8317        init_test(cx);
 8318
 8319        let fs = FakeFs::new(cx.executor());
 8320        let project = Project::test(fs, [], cx).await;
 8321        let (workspace, cx) =
 8322            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8323
 8324        // Adding an item with no ambiguity renders the tab without detail.
 8325        let item1 = cx.new(|cx| {
 8326            let mut item = TestItem::new(cx);
 8327            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8328            item
 8329        });
 8330        workspace.update_in(cx, |workspace, window, cx| {
 8331            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8332        });
 8333        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8334
 8335        // Adding an item that creates ambiguity increases the level of detail on
 8336        // both tabs.
 8337        let item2 = cx.new_window_entity(|_window, cx| {
 8338            let mut item = TestItem::new(cx);
 8339            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8340            item
 8341        });
 8342        workspace.update_in(cx, |workspace, window, cx| {
 8343            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8344        });
 8345        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8346        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8347
 8348        // Adding an item that creates ambiguity increases the level of detail only
 8349        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8350        // we stop at the highest detail available.
 8351        let item3 = cx.new(|cx| {
 8352            let mut item = TestItem::new(cx);
 8353            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8354            item
 8355        });
 8356        workspace.update_in(cx, |workspace, window, cx| {
 8357            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8358        });
 8359        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8360        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8361        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8362    }
 8363
 8364    #[gpui::test]
 8365    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8366        init_test(cx);
 8367
 8368        let fs = FakeFs::new(cx.executor());
 8369        fs.insert_tree(
 8370            "/root1",
 8371            json!({
 8372                "one.txt": "",
 8373                "two.txt": "",
 8374            }),
 8375        )
 8376        .await;
 8377        fs.insert_tree(
 8378            "/root2",
 8379            json!({
 8380                "three.txt": "",
 8381            }),
 8382        )
 8383        .await;
 8384
 8385        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8386        let (workspace, cx) =
 8387            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8388        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8389        let worktree_id = project.update(cx, |project, cx| {
 8390            project.worktrees(cx).next().unwrap().read(cx).id()
 8391        });
 8392
 8393        let item1 = cx.new(|cx| {
 8394            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8395        });
 8396        let item2 = cx.new(|cx| {
 8397            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8398        });
 8399
 8400        // Add an item to an empty pane
 8401        workspace.update_in(cx, |workspace, window, cx| {
 8402            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8403        });
 8404        project.update(cx, |project, cx| {
 8405            assert_eq!(
 8406                project.active_entry(),
 8407                project
 8408                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8409                    .map(|e| e.id)
 8410            );
 8411        });
 8412        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8413
 8414        // Add a second item to a non-empty pane
 8415        workspace.update_in(cx, |workspace, window, cx| {
 8416            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8417        });
 8418        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8419        project.update(cx, |project, cx| {
 8420            assert_eq!(
 8421                project.active_entry(),
 8422                project
 8423                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 8424                    .map(|e| e.id)
 8425            );
 8426        });
 8427
 8428        // Close the active item
 8429        pane.update_in(cx, |pane, window, cx| {
 8430            pane.close_active_item(&Default::default(), window, cx)
 8431        })
 8432        .await
 8433        .unwrap();
 8434        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8435        project.update(cx, |project, cx| {
 8436            assert_eq!(
 8437                project.active_entry(),
 8438                project
 8439                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8440                    .map(|e| e.id)
 8441            );
 8442        });
 8443
 8444        // Add a project folder
 8445        project
 8446            .update(cx, |project, cx| {
 8447                project.find_or_create_worktree("root2", true, cx)
 8448            })
 8449            .await
 8450            .unwrap();
 8451        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8452
 8453        // Remove a project folder
 8454        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8455        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8456    }
 8457
 8458    #[gpui::test]
 8459    async fn test_close_window(cx: &mut TestAppContext) {
 8460        init_test(cx);
 8461
 8462        let fs = FakeFs::new(cx.executor());
 8463        fs.insert_tree("/root", json!({ "one": "" })).await;
 8464
 8465        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8466        let (workspace, cx) =
 8467            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8468
 8469        // When there are no dirty items, there's nothing to do.
 8470        let item1 = cx.new(TestItem::new);
 8471        workspace.update_in(cx, |w, window, cx| {
 8472            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8473        });
 8474        let task = workspace.update_in(cx, |w, window, cx| {
 8475            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8476        });
 8477        assert!(task.await.unwrap());
 8478
 8479        // When there are dirty untitled items, prompt to save each one. If the user
 8480        // cancels any prompt, then abort.
 8481        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8482        let item3 = cx.new(|cx| {
 8483            TestItem::new(cx)
 8484                .with_dirty(true)
 8485                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8486        });
 8487        workspace.update_in(cx, |w, window, cx| {
 8488            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8489            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8490        });
 8491        let task = workspace.update_in(cx, |w, window, cx| {
 8492            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8493        });
 8494        cx.executor().run_until_parked();
 8495        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8496        cx.executor().run_until_parked();
 8497        assert!(!cx.has_pending_prompt());
 8498        assert!(!task.await.unwrap());
 8499    }
 8500
 8501    #[gpui::test]
 8502    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8503        init_test(cx);
 8504
 8505        // Register TestItem as a serializable item
 8506        cx.update(|cx| {
 8507            register_serializable_item::<TestItem>(cx);
 8508        });
 8509
 8510        let fs = FakeFs::new(cx.executor());
 8511        fs.insert_tree("/root", json!({ "one": "" })).await;
 8512
 8513        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8514        let (workspace, cx) =
 8515            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8516
 8517        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8518        let item1 = cx.new(|cx| {
 8519            TestItem::new(cx)
 8520                .with_dirty(true)
 8521                .with_serialize(|| Some(Task::ready(Ok(()))))
 8522        });
 8523        let item2 = cx.new(|cx| {
 8524            TestItem::new(cx)
 8525                .with_dirty(true)
 8526                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8527                .with_serialize(|| Some(Task::ready(Ok(()))))
 8528        });
 8529        workspace.update_in(cx, |w, window, cx| {
 8530            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8531            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8532        });
 8533        let task = workspace.update_in(cx, |w, window, cx| {
 8534            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8535        });
 8536        assert!(task.await.unwrap());
 8537    }
 8538
 8539    #[gpui::test]
 8540    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8541        init_test(cx);
 8542
 8543        let fs = FakeFs::new(cx.executor());
 8544
 8545        let project = Project::test(fs, None, cx).await;
 8546        let (workspace, cx) =
 8547            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8548
 8549        let item1 = cx.new(|cx| {
 8550            TestItem::new(cx)
 8551                .with_dirty(true)
 8552                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8553        });
 8554        let item2 = cx.new(|cx| {
 8555            TestItem::new(cx)
 8556                .with_dirty(true)
 8557                .with_conflict(true)
 8558                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8559        });
 8560        let item3 = cx.new(|cx| {
 8561            TestItem::new(cx)
 8562                .with_dirty(true)
 8563                .with_conflict(true)
 8564                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8565        });
 8566        let item4 = cx.new(|cx| {
 8567            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8568                let project_item = TestProjectItem::new_untitled(cx);
 8569                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8570                project_item
 8571            }])
 8572        });
 8573        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8574            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8575            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8576            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8577            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8578            workspace.active_pane().clone()
 8579        });
 8580
 8581        let close_items = pane.update_in(cx, |pane, window, cx| {
 8582            pane.activate_item(1, true, true, window, cx);
 8583            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8584            let item1_id = item1.item_id();
 8585            let item3_id = item3.item_id();
 8586            let item4_id = item4.item_id();
 8587            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8588                [item1_id, item3_id, item4_id].contains(&id)
 8589            })
 8590        });
 8591        cx.executor().run_until_parked();
 8592
 8593        assert!(cx.has_pending_prompt());
 8594        cx.simulate_prompt_answer("Save all");
 8595
 8596        cx.executor().run_until_parked();
 8597
 8598        // Item 1 is saved. There's a prompt to save item 3.
 8599        pane.update(cx, |pane, cx| {
 8600            assert_eq!(item1.read(cx).save_count, 1);
 8601            assert_eq!(item1.read(cx).save_as_count, 0);
 8602            assert_eq!(item1.read(cx).reload_count, 0);
 8603            assert_eq!(pane.items_len(), 3);
 8604            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8605        });
 8606        assert!(cx.has_pending_prompt());
 8607
 8608        // Cancel saving item 3.
 8609        cx.simulate_prompt_answer("Discard");
 8610        cx.executor().run_until_parked();
 8611
 8612        // Item 3 is reloaded. There's a prompt to save item 4.
 8613        pane.update(cx, |pane, cx| {
 8614            assert_eq!(item3.read(cx).save_count, 0);
 8615            assert_eq!(item3.read(cx).save_as_count, 0);
 8616            assert_eq!(item3.read(cx).reload_count, 1);
 8617            assert_eq!(pane.items_len(), 2);
 8618            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8619        });
 8620
 8621        // There's a prompt for a path for item 4.
 8622        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8623        close_items.await.unwrap();
 8624
 8625        // The requested items are closed.
 8626        pane.update(cx, |pane, cx| {
 8627            assert_eq!(item4.read(cx).save_count, 0);
 8628            assert_eq!(item4.read(cx).save_as_count, 1);
 8629            assert_eq!(item4.read(cx).reload_count, 0);
 8630            assert_eq!(pane.items_len(), 1);
 8631            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8632        });
 8633    }
 8634
 8635    #[gpui::test]
 8636    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8637        init_test(cx);
 8638
 8639        let fs = FakeFs::new(cx.executor());
 8640        let project = Project::test(fs, [], cx).await;
 8641        let (workspace, cx) =
 8642            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8643
 8644        // Create several workspace items with single project entries, and two
 8645        // workspace items with multiple project entries.
 8646        let single_entry_items = (0..=4)
 8647            .map(|project_entry_id| {
 8648                cx.new(|cx| {
 8649                    TestItem::new(cx)
 8650                        .with_dirty(true)
 8651                        .with_project_items(&[dirty_project_item(
 8652                            project_entry_id,
 8653                            &format!("{project_entry_id}.txt"),
 8654                            cx,
 8655                        )])
 8656                })
 8657            })
 8658            .collect::<Vec<_>>();
 8659        let item_2_3 = cx.new(|cx| {
 8660            TestItem::new(cx)
 8661                .with_dirty(true)
 8662                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8663                .with_project_items(&[
 8664                    single_entry_items[2].read(cx).project_items[0].clone(),
 8665                    single_entry_items[3].read(cx).project_items[0].clone(),
 8666                ])
 8667        });
 8668        let item_3_4 = cx.new(|cx| {
 8669            TestItem::new(cx)
 8670                .with_dirty(true)
 8671                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8672                .with_project_items(&[
 8673                    single_entry_items[3].read(cx).project_items[0].clone(),
 8674                    single_entry_items[4].read(cx).project_items[0].clone(),
 8675                ])
 8676        });
 8677
 8678        // Create two panes that contain the following project entries:
 8679        //   left pane:
 8680        //     multi-entry items:   (2, 3)
 8681        //     single-entry items:  0, 2, 3, 4
 8682        //   right pane:
 8683        //     single-entry items:  4, 1
 8684        //     multi-entry items:   (3, 4)
 8685        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8686            let left_pane = workspace.active_pane().clone();
 8687            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8688            workspace.add_item_to_active_pane(
 8689                single_entry_items[0].boxed_clone(),
 8690                None,
 8691                true,
 8692                window,
 8693                cx,
 8694            );
 8695            workspace.add_item_to_active_pane(
 8696                single_entry_items[2].boxed_clone(),
 8697                None,
 8698                true,
 8699                window,
 8700                cx,
 8701            );
 8702            workspace.add_item_to_active_pane(
 8703                single_entry_items[3].boxed_clone(),
 8704                None,
 8705                true,
 8706                window,
 8707                cx,
 8708            );
 8709            workspace.add_item_to_active_pane(
 8710                single_entry_items[4].boxed_clone(),
 8711                None,
 8712                true,
 8713                window,
 8714                cx,
 8715            );
 8716
 8717            let right_pane =
 8718                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 8719
 8720            let boxed_clone = single_entry_items[1].boxed_clone();
 8721            let right_pane = window.spawn(cx, async move |cx| {
 8722                right_pane.await.inspect(|right_pane| {
 8723                    right_pane
 8724                        .update_in(cx, |pane, window, cx| {
 8725                            pane.add_item(boxed_clone, true, true, None, window, cx);
 8726                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8727                        })
 8728                        .unwrap();
 8729                })
 8730            });
 8731
 8732            (left_pane, right_pane)
 8733        });
 8734        let right_pane = right_pane.await.unwrap();
 8735        cx.focus(&right_pane);
 8736
 8737        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8738            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8739                .unwrap()
 8740        });
 8741        cx.executor().run_until_parked();
 8742
 8743        let msg = cx.pending_prompt().unwrap().0;
 8744        assert!(msg.contains("1.txt"));
 8745        assert!(!msg.contains("2.txt"));
 8746        assert!(!msg.contains("3.txt"));
 8747        assert!(!msg.contains("4.txt"));
 8748
 8749        cx.simulate_prompt_answer("Cancel");
 8750        close.await;
 8751
 8752        left_pane
 8753            .update_in(cx, |left_pane, window, cx| {
 8754                left_pane.close_item_by_id(
 8755                    single_entry_items[3].entity_id(),
 8756                    SaveIntent::Skip,
 8757                    window,
 8758                    cx,
 8759                )
 8760            })
 8761            .await
 8762            .unwrap();
 8763
 8764        close = right_pane.update_in(cx, |pane, window, cx| {
 8765            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8766                .unwrap()
 8767        });
 8768        cx.executor().run_until_parked();
 8769
 8770        let details = cx.pending_prompt().unwrap().1;
 8771        assert!(details.contains("1.txt"));
 8772        assert!(!details.contains("2.txt"));
 8773        assert!(details.contains("3.txt"));
 8774        // ideally this assertion could be made, but today we can only
 8775        // save whole items not project items, so the orphaned item 3 causes
 8776        // 4 to be saved too.
 8777        // assert!(!details.contains("4.txt"));
 8778
 8779        cx.simulate_prompt_answer("Save all");
 8780
 8781        cx.executor().run_until_parked();
 8782        close.await;
 8783        right_pane.read_with(cx, |pane, _| {
 8784            assert_eq!(pane.items_len(), 0);
 8785        });
 8786    }
 8787
 8788    #[gpui::test]
 8789    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8790        init_test(cx);
 8791
 8792        let fs = FakeFs::new(cx.executor());
 8793        let project = Project::test(fs, [], cx).await;
 8794        let (workspace, cx) =
 8795            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8796        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8797
 8798        let item = cx.new(|cx| {
 8799            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8800        });
 8801        let item_id = item.entity_id();
 8802        workspace.update_in(cx, |workspace, window, cx| {
 8803            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8804        });
 8805
 8806        // Autosave on window change.
 8807        item.update(cx, |item, cx| {
 8808            SettingsStore::update_global(cx, |settings, cx| {
 8809                settings.update_user_settings(cx, |settings| {
 8810                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 8811                })
 8812            });
 8813            item.is_dirty = true;
 8814        });
 8815
 8816        // Deactivating the window saves the file.
 8817        cx.deactivate_window();
 8818        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8819
 8820        // Re-activating the window doesn't save the file.
 8821        cx.update(|window, _| window.activate_window());
 8822        cx.executor().run_until_parked();
 8823        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8824
 8825        // Autosave on focus change.
 8826        item.update_in(cx, |item, window, cx| {
 8827            cx.focus_self(window);
 8828            SettingsStore::update_global(cx, |settings, cx| {
 8829                settings.update_user_settings(cx, |settings| {
 8830                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 8831                })
 8832            });
 8833            item.is_dirty = true;
 8834        });
 8835        // Blurring the item saves the file.
 8836        item.update_in(cx, |_, window, _| window.blur());
 8837        cx.executor().run_until_parked();
 8838        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8839
 8840        // Deactivating the window still saves the file.
 8841        item.update_in(cx, |item, window, cx| {
 8842            cx.focus_self(window);
 8843            item.is_dirty = true;
 8844        });
 8845        cx.deactivate_window();
 8846        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8847
 8848        // Autosave after delay.
 8849        item.update(cx, |item, cx| {
 8850            SettingsStore::update_global(cx, |settings, cx| {
 8851                settings.update_user_settings(cx, |settings| {
 8852                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 8853                        milliseconds: 500.into(),
 8854                    });
 8855                })
 8856            });
 8857            item.is_dirty = true;
 8858            cx.emit(ItemEvent::Edit);
 8859        });
 8860
 8861        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8862        cx.executor().advance_clock(Duration::from_millis(250));
 8863        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8864
 8865        // After delay expires, the file is saved.
 8866        cx.executor().advance_clock(Duration::from_millis(250));
 8867        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8868
 8869        // Autosave after delay, should save earlier than delay if tab is closed
 8870        item.update(cx, |item, cx| {
 8871            item.is_dirty = true;
 8872            cx.emit(ItemEvent::Edit);
 8873        });
 8874        cx.executor().advance_clock(Duration::from_millis(250));
 8875        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8876
 8877        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 8878        pane.update_in(cx, |pane, window, cx| {
 8879            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8880        })
 8881        .await
 8882        .unwrap();
 8883        assert!(!cx.has_pending_prompt());
 8884        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8885
 8886        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8887        workspace.update_in(cx, |workspace, window, cx| {
 8888            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8889        });
 8890        item.update_in(cx, |item, _window, cx| {
 8891            item.is_dirty = true;
 8892            for project_item in &mut item.project_items {
 8893                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8894            }
 8895        });
 8896        cx.run_until_parked();
 8897        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8898
 8899        // Autosave on focus change, ensuring closing the tab counts as such.
 8900        item.update(cx, |item, cx| {
 8901            SettingsStore::update_global(cx, |settings, cx| {
 8902                settings.update_user_settings(cx, |settings| {
 8903                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 8904                })
 8905            });
 8906            item.is_dirty = true;
 8907            for project_item in &mut item.project_items {
 8908                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8909            }
 8910        });
 8911
 8912        pane.update_in(cx, |pane, window, cx| {
 8913            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8914        })
 8915        .await
 8916        .unwrap();
 8917        assert!(!cx.has_pending_prompt());
 8918        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8919
 8920        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8921        workspace.update_in(cx, |workspace, window, cx| {
 8922            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8923        });
 8924        item.update_in(cx, |item, window, cx| {
 8925            item.project_items[0].update(cx, |item, _| {
 8926                item.entry_id = None;
 8927            });
 8928            item.is_dirty = true;
 8929            window.blur();
 8930        });
 8931        cx.run_until_parked();
 8932        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8933
 8934        // Ensure autosave is prevented for deleted files also when closing the buffer.
 8935        let _close_items = pane.update_in(cx, |pane, window, cx| {
 8936            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8937        });
 8938        cx.run_until_parked();
 8939        assert!(cx.has_pending_prompt());
 8940        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8941    }
 8942
 8943    #[gpui::test]
 8944    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 8945        init_test(cx);
 8946
 8947        let fs = FakeFs::new(cx.executor());
 8948
 8949        let project = Project::test(fs, [], cx).await;
 8950        let (workspace, cx) =
 8951            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8952
 8953        let item = cx.new(|cx| {
 8954            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8955        });
 8956        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8957        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 8958        let toolbar_notify_count = Rc::new(RefCell::new(0));
 8959
 8960        workspace.update_in(cx, |workspace, window, cx| {
 8961            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8962            let toolbar_notification_count = toolbar_notify_count.clone();
 8963            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 8964                *toolbar_notification_count.borrow_mut() += 1
 8965            })
 8966            .detach();
 8967        });
 8968
 8969        pane.read_with(cx, |pane, _| {
 8970            assert!(!pane.can_navigate_backward());
 8971            assert!(!pane.can_navigate_forward());
 8972        });
 8973
 8974        item.update_in(cx, |item, _, cx| {
 8975            item.set_state("one".to_string(), cx);
 8976        });
 8977
 8978        // Toolbar must be notified to re-render the navigation buttons
 8979        assert_eq!(*toolbar_notify_count.borrow(), 1);
 8980
 8981        pane.read_with(cx, |pane, _| {
 8982            assert!(pane.can_navigate_backward());
 8983            assert!(!pane.can_navigate_forward());
 8984        });
 8985
 8986        workspace
 8987            .update_in(cx, |workspace, window, cx| {
 8988                workspace.go_back(pane.downgrade(), window, cx)
 8989            })
 8990            .await
 8991            .unwrap();
 8992
 8993        assert_eq!(*toolbar_notify_count.borrow(), 2);
 8994        pane.read_with(cx, |pane, _| {
 8995            assert!(!pane.can_navigate_backward());
 8996            assert!(pane.can_navigate_forward());
 8997        });
 8998    }
 8999
 9000    #[gpui::test]
 9001    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9002        init_test(cx);
 9003        let fs = FakeFs::new(cx.executor());
 9004
 9005        let project = Project::test(fs, [], cx).await;
 9006        let (workspace, cx) =
 9007            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9008
 9009        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9010            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9011            workspace.add_panel(panel.clone(), window, cx);
 9012
 9013            workspace
 9014                .right_dock()
 9015                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9016
 9017            panel
 9018        });
 9019
 9020        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9021        pane.update_in(cx, |pane, window, cx| {
 9022            let item = cx.new(TestItem::new);
 9023            pane.add_item(Box::new(item), true, true, None, window, cx);
 9024        });
 9025
 9026        // Transfer focus from center to panel
 9027        workspace.update_in(cx, |workspace, window, cx| {
 9028            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9029        });
 9030
 9031        workspace.update_in(cx, |workspace, window, cx| {
 9032            assert!(workspace.right_dock().read(cx).is_open());
 9033            assert!(!panel.is_zoomed(window, cx));
 9034            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9035        });
 9036
 9037        // Transfer focus from panel to center
 9038        workspace.update_in(cx, |workspace, window, cx| {
 9039            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9040        });
 9041
 9042        workspace.update_in(cx, |workspace, window, cx| {
 9043            assert!(workspace.right_dock().read(cx).is_open());
 9044            assert!(!panel.is_zoomed(window, cx));
 9045            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9046        });
 9047
 9048        // Close the dock
 9049        workspace.update_in(cx, |workspace, window, cx| {
 9050            workspace.toggle_dock(DockPosition::Right, window, cx);
 9051        });
 9052
 9053        workspace.update_in(cx, |workspace, window, cx| {
 9054            assert!(!workspace.right_dock().read(cx).is_open());
 9055            assert!(!panel.is_zoomed(window, cx));
 9056            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9057        });
 9058
 9059        // Open the dock
 9060        workspace.update_in(cx, |workspace, window, cx| {
 9061            workspace.toggle_dock(DockPosition::Right, window, cx);
 9062        });
 9063
 9064        workspace.update_in(cx, |workspace, window, cx| {
 9065            assert!(workspace.right_dock().read(cx).is_open());
 9066            assert!(!panel.is_zoomed(window, cx));
 9067            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9068        });
 9069
 9070        // Focus and zoom panel
 9071        panel.update_in(cx, |panel, window, cx| {
 9072            cx.focus_self(window);
 9073            panel.set_zoomed(true, window, cx)
 9074        });
 9075
 9076        workspace.update_in(cx, |workspace, window, cx| {
 9077            assert!(workspace.right_dock().read(cx).is_open());
 9078            assert!(panel.is_zoomed(window, cx));
 9079            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9080        });
 9081
 9082        // Transfer focus to the center closes the dock
 9083        workspace.update_in(cx, |workspace, window, cx| {
 9084            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9085        });
 9086
 9087        workspace.update_in(cx, |workspace, window, cx| {
 9088            assert!(!workspace.right_dock().read(cx).is_open());
 9089            assert!(panel.is_zoomed(window, cx));
 9090            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9091        });
 9092
 9093        // Transferring focus back to the panel keeps it zoomed
 9094        workspace.update_in(cx, |workspace, window, cx| {
 9095            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9096        });
 9097
 9098        workspace.update_in(cx, |workspace, window, cx| {
 9099            assert!(workspace.right_dock().read(cx).is_open());
 9100            assert!(panel.is_zoomed(window, cx));
 9101            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9102        });
 9103
 9104        // Close the dock while it is zoomed
 9105        workspace.update_in(cx, |workspace, window, cx| {
 9106            workspace.toggle_dock(DockPosition::Right, window, cx)
 9107        });
 9108
 9109        workspace.update_in(cx, |workspace, window, cx| {
 9110            assert!(!workspace.right_dock().read(cx).is_open());
 9111            assert!(panel.is_zoomed(window, cx));
 9112            assert!(workspace.zoomed.is_none());
 9113            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9114        });
 9115
 9116        // Opening the dock, when it's zoomed, retains focus
 9117        workspace.update_in(cx, |workspace, window, cx| {
 9118            workspace.toggle_dock(DockPosition::Right, window, cx)
 9119        });
 9120
 9121        workspace.update_in(cx, |workspace, window, cx| {
 9122            assert!(workspace.right_dock().read(cx).is_open());
 9123            assert!(panel.is_zoomed(window, cx));
 9124            assert!(workspace.zoomed.is_some());
 9125            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9126        });
 9127
 9128        // Unzoom and close the panel, zoom the active pane.
 9129        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9130        workspace.update_in(cx, |workspace, window, cx| {
 9131            workspace.toggle_dock(DockPosition::Right, window, cx)
 9132        });
 9133        pane.update_in(cx, |pane, window, cx| {
 9134            pane.toggle_zoom(&Default::default(), window, cx)
 9135        });
 9136
 9137        // Opening a dock unzooms the pane.
 9138        workspace.update_in(cx, |workspace, window, cx| {
 9139            workspace.toggle_dock(DockPosition::Right, window, cx)
 9140        });
 9141        workspace.update_in(cx, |workspace, window, cx| {
 9142            let pane = pane.read(cx);
 9143            assert!(!pane.is_zoomed());
 9144            assert!(!pane.focus_handle(cx).is_focused(window));
 9145            assert!(workspace.right_dock().read(cx).is_open());
 9146            assert!(workspace.zoomed.is_none());
 9147        });
 9148    }
 9149
 9150    #[gpui::test]
 9151    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 9152        init_test(cx);
 9153
 9154        let fs = FakeFs::new(cx.executor());
 9155
 9156        let project = Project::test(fs, None, cx).await;
 9157        let (workspace, cx) =
 9158            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9159
 9160        // Let's arrange the panes like this:
 9161        //
 9162        // +-----------------------+
 9163        // |         top           |
 9164        // +------+--------+-------+
 9165        // | left | center | right |
 9166        // +------+--------+-------+
 9167        // |        bottom         |
 9168        // +-----------------------+
 9169
 9170        let top_item = cx.new(|cx| {
 9171            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 9172        });
 9173        let bottom_item = cx.new(|cx| {
 9174            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 9175        });
 9176        let left_item = cx.new(|cx| {
 9177            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 9178        });
 9179        let right_item = cx.new(|cx| {
 9180            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 9181        });
 9182        let center_item = cx.new(|cx| {
 9183            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 9184        });
 9185
 9186        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9187            let top_pane_id = workspace.active_pane().entity_id();
 9188            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 9189            workspace.split_pane(
 9190                workspace.active_pane().clone(),
 9191                SplitDirection::Down,
 9192                window,
 9193                cx,
 9194            );
 9195            top_pane_id
 9196        });
 9197        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9198            let bottom_pane_id = workspace.active_pane().entity_id();
 9199            workspace.add_item_to_active_pane(
 9200                Box::new(bottom_item.clone()),
 9201                None,
 9202                false,
 9203                window,
 9204                cx,
 9205            );
 9206            workspace.split_pane(
 9207                workspace.active_pane().clone(),
 9208                SplitDirection::Up,
 9209                window,
 9210                cx,
 9211            );
 9212            bottom_pane_id
 9213        });
 9214        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9215            let left_pane_id = workspace.active_pane().entity_id();
 9216            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 9217            workspace.split_pane(
 9218                workspace.active_pane().clone(),
 9219                SplitDirection::Right,
 9220                window,
 9221                cx,
 9222            );
 9223            left_pane_id
 9224        });
 9225        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9226            let right_pane_id = workspace.active_pane().entity_id();
 9227            workspace.add_item_to_active_pane(
 9228                Box::new(right_item.clone()),
 9229                None,
 9230                false,
 9231                window,
 9232                cx,
 9233            );
 9234            workspace.split_pane(
 9235                workspace.active_pane().clone(),
 9236                SplitDirection::Left,
 9237                window,
 9238                cx,
 9239            );
 9240            right_pane_id
 9241        });
 9242        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9243            let center_pane_id = workspace.active_pane().entity_id();
 9244            workspace.add_item_to_active_pane(
 9245                Box::new(center_item.clone()),
 9246                None,
 9247                false,
 9248                window,
 9249                cx,
 9250            );
 9251            center_pane_id
 9252        });
 9253        cx.executor().run_until_parked();
 9254
 9255        workspace.update_in(cx, |workspace, window, cx| {
 9256            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9257
 9258            // Join into next from center pane into right
 9259            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9260        });
 9261
 9262        workspace.update_in(cx, |workspace, window, cx| {
 9263            let active_pane = workspace.active_pane();
 9264            assert_eq!(right_pane_id, active_pane.entity_id());
 9265            assert_eq!(2, active_pane.read(cx).items_len());
 9266            let item_ids_in_pane =
 9267                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9268            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9269            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9270
 9271            // Join into next from right pane into bottom
 9272            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9273        });
 9274
 9275        workspace.update_in(cx, |workspace, window, cx| {
 9276            let active_pane = workspace.active_pane();
 9277            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9278            assert_eq!(3, active_pane.read(cx).items_len());
 9279            let item_ids_in_pane =
 9280                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9281            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9282            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9283            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9284
 9285            // Join into next from bottom pane into left
 9286            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9287        });
 9288
 9289        workspace.update_in(cx, |workspace, window, cx| {
 9290            let active_pane = workspace.active_pane();
 9291            assert_eq!(left_pane_id, active_pane.entity_id());
 9292            assert_eq!(4, active_pane.read(cx).items_len());
 9293            let item_ids_in_pane =
 9294                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9295            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9296            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9297            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9298            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9299
 9300            // Join into next from left pane into top
 9301            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9302        });
 9303
 9304        workspace.update_in(cx, |workspace, window, cx| {
 9305            let active_pane = workspace.active_pane();
 9306            assert_eq!(top_pane_id, active_pane.entity_id());
 9307            assert_eq!(5, active_pane.read(cx).items_len());
 9308            let item_ids_in_pane =
 9309                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9310            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9311            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9312            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9313            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9314            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9315
 9316            // Single pane left: no-op
 9317            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9318        });
 9319
 9320        workspace.update(cx, |workspace, _cx| {
 9321            let active_pane = workspace.active_pane();
 9322            assert_eq!(top_pane_id, active_pane.entity_id());
 9323        });
 9324    }
 9325
 9326    fn add_an_item_to_active_pane(
 9327        cx: &mut VisualTestContext,
 9328        workspace: &Entity<Workspace>,
 9329        item_id: u64,
 9330    ) -> Entity<TestItem> {
 9331        let item = cx.new(|cx| {
 9332            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9333                item_id,
 9334                "item{item_id}.txt",
 9335                cx,
 9336            )])
 9337        });
 9338        workspace.update_in(cx, |workspace, window, cx| {
 9339            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9340        });
 9341        item
 9342    }
 9343
 9344    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9345        workspace.update_in(cx, |workspace, window, cx| {
 9346            workspace.split_pane(
 9347                workspace.active_pane().clone(),
 9348                SplitDirection::Right,
 9349                window,
 9350                cx,
 9351            )
 9352        })
 9353    }
 9354
 9355    #[gpui::test]
 9356    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9357        init_test(cx);
 9358        let fs = FakeFs::new(cx.executor());
 9359        let project = Project::test(fs, None, cx).await;
 9360        let (workspace, cx) =
 9361            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9362
 9363        add_an_item_to_active_pane(cx, &workspace, 1);
 9364        split_pane(cx, &workspace);
 9365        add_an_item_to_active_pane(cx, &workspace, 2);
 9366        split_pane(cx, &workspace); // empty pane
 9367        split_pane(cx, &workspace);
 9368        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9369
 9370        cx.executor().run_until_parked();
 9371
 9372        workspace.update(cx, |workspace, cx| {
 9373            let num_panes = workspace.panes().len();
 9374            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9375            let active_item = workspace
 9376                .active_pane()
 9377                .read(cx)
 9378                .active_item()
 9379                .expect("item is in focus");
 9380
 9381            assert_eq!(num_panes, 4);
 9382            assert_eq!(num_items_in_current_pane, 1);
 9383            assert_eq!(active_item.item_id(), last_item.item_id());
 9384        });
 9385
 9386        workspace.update_in(cx, |workspace, window, cx| {
 9387            workspace.join_all_panes(window, cx);
 9388        });
 9389
 9390        workspace.update(cx, |workspace, cx| {
 9391            let num_panes = workspace.panes().len();
 9392            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9393            let active_item = workspace
 9394                .active_pane()
 9395                .read(cx)
 9396                .active_item()
 9397                .expect("item is in focus");
 9398
 9399            assert_eq!(num_panes, 1);
 9400            assert_eq!(num_items_in_current_pane, 3);
 9401            assert_eq!(active_item.item_id(), last_item.item_id());
 9402        });
 9403    }
 9404    struct TestModal(FocusHandle);
 9405
 9406    impl TestModal {
 9407        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9408            Self(cx.focus_handle())
 9409        }
 9410    }
 9411
 9412    impl EventEmitter<DismissEvent> for TestModal {}
 9413
 9414    impl Focusable for TestModal {
 9415        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9416            self.0.clone()
 9417        }
 9418    }
 9419
 9420    impl ModalView for TestModal {}
 9421
 9422    impl Render for TestModal {
 9423        fn render(
 9424            &mut self,
 9425            _window: &mut Window,
 9426            _cx: &mut Context<TestModal>,
 9427        ) -> impl IntoElement {
 9428            div().track_focus(&self.0)
 9429        }
 9430    }
 9431
 9432    #[gpui::test]
 9433    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9434        init_test(cx);
 9435        let fs = FakeFs::new(cx.executor());
 9436
 9437        let project = Project::test(fs, [], cx).await;
 9438        let (workspace, cx) =
 9439            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9440
 9441        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9442            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9443            workspace.add_panel(panel_1.clone(), window, cx);
 9444            workspace.toggle_dock(DockPosition::Left, window, cx);
 9445            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9446            workspace.add_panel(panel_2.clone(), window, cx);
 9447            workspace.toggle_dock(DockPosition::Right, window, cx);
 9448
 9449            let left_dock = workspace.left_dock();
 9450            assert_eq!(
 9451                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9452                panel_1.panel_id()
 9453            );
 9454            assert_eq!(
 9455                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9456                panel_1.size(window, cx)
 9457            );
 9458
 9459            left_dock.update(cx, |left_dock, cx| {
 9460                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9461            });
 9462            assert_eq!(
 9463                workspace
 9464                    .right_dock()
 9465                    .read(cx)
 9466                    .visible_panel()
 9467                    .unwrap()
 9468                    .panel_id(),
 9469                panel_2.panel_id(),
 9470            );
 9471
 9472            (panel_1, panel_2)
 9473        });
 9474
 9475        // Move panel_1 to the right
 9476        panel_1.update_in(cx, |panel_1, window, cx| {
 9477            panel_1.set_position(DockPosition::Right, window, cx)
 9478        });
 9479
 9480        workspace.update_in(cx, |workspace, window, cx| {
 9481            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9482            // Since it was the only panel on the left, the left dock should now be closed.
 9483            assert!(!workspace.left_dock().read(cx).is_open());
 9484            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9485            let right_dock = workspace.right_dock();
 9486            assert_eq!(
 9487                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9488                panel_1.panel_id()
 9489            );
 9490            assert_eq!(
 9491                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9492                px(1337.)
 9493            );
 9494
 9495            // Now we move panel_2 to the left
 9496            panel_2.set_position(DockPosition::Left, window, cx);
 9497        });
 9498
 9499        workspace.update(cx, |workspace, cx| {
 9500            // Since panel_2 was not visible on the right, we don't open the left dock.
 9501            assert!(!workspace.left_dock().read(cx).is_open());
 9502            // And the right dock is unaffected in its displaying of panel_1
 9503            assert!(workspace.right_dock().read(cx).is_open());
 9504            assert_eq!(
 9505                workspace
 9506                    .right_dock()
 9507                    .read(cx)
 9508                    .visible_panel()
 9509                    .unwrap()
 9510                    .panel_id(),
 9511                panel_1.panel_id(),
 9512            );
 9513        });
 9514
 9515        // Move panel_1 back to the left
 9516        panel_1.update_in(cx, |panel_1, window, cx| {
 9517            panel_1.set_position(DockPosition::Left, window, cx)
 9518        });
 9519
 9520        workspace.update_in(cx, |workspace, window, cx| {
 9521            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9522            let left_dock = workspace.left_dock();
 9523            assert!(left_dock.read(cx).is_open());
 9524            assert_eq!(
 9525                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9526                panel_1.panel_id()
 9527            );
 9528            assert_eq!(
 9529                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9530                px(1337.)
 9531            );
 9532            // And the right dock should be closed as it no longer has any panels.
 9533            assert!(!workspace.right_dock().read(cx).is_open());
 9534
 9535            // Now we move panel_1 to the bottom
 9536            panel_1.set_position(DockPosition::Bottom, window, cx);
 9537        });
 9538
 9539        workspace.update_in(cx, |workspace, window, cx| {
 9540            // Since panel_1 was visible on the left, we close the left dock.
 9541            assert!(!workspace.left_dock().read(cx).is_open());
 9542            // The bottom dock is sized based on the panel's default size,
 9543            // since the panel orientation changed from vertical to horizontal.
 9544            let bottom_dock = workspace.bottom_dock();
 9545            assert_eq!(
 9546                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9547                panel_1.size(window, cx),
 9548            );
 9549            // Close bottom dock and move panel_1 back to the left.
 9550            bottom_dock.update(cx, |bottom_dock, cx| {
 9551                bottom_dock.set_open(false, window, cx)
 9552            });
 9553            panel_1.set_position(DockPosition::Left, window, cx);
 9554        });
 9555
 9556        // Emit activated event on panel 1
 9557        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9558
 9559        // Now the left dock is open and panel_1 is active and focused.
 9560        workspace.update_in(cx, |workspace, window, cx| {
 9561            let left_dock = workspace.left_dock();
 9562            assert!(left_dock.read(cx).is_open());
 9563            assert_eq!(
 9564                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9565                panel_1.panel_id(),
 9566            );
 9567            assert!(panel_1.focus_handle(cx).is_focused(window));
 9568        });
 9569
 9570        // Emit closed event on panel 2, which is not active
 9571        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9572
 9573        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9574        workspace.update(cx, |workspace, cx| {
 9575            let left_dock = workspace.left_dock();
 9576            assert!(left_dock.read(cx).is_open());
 9577            assert_eq!(
 9578                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9579                panel_1.panel_id(),
 9580            );
 9581        });
 9582
 9583        // Emitting a ZoomIn event shows the panel as zoomed.
 9584        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9585        workspace.read_with(cx, |workspace, _| {
 9586            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9587            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9588        });
 9589
 9590        // Move panel to another dock while it is zoomed
 9591        panel_1.update_in(cx, |panel, window, cx| {
 9592            panel.set_position(DockPosition::Right, window, cx)
 9593        });
 9594        workspace.read_with(cx, |workspace, _| {
 9595            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9596
 9597            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9598        });
 9599
 9600        // This is a helper for getting a:
 9601        // - valid focus on an element,
 9602        // - that isn't a part of the panes and panels system of the Workspace,
 9603        // - and doesn't trigger the 'on_focus_lost' API.
 9604        let focus_other_view = {
 9605            let workspace = workspace.clone();
 9606            move |cx: &mut VisualTestContext| {
 9607                workspace.update_in(cx, |workspace, window, cx| {
 9608                    if workspace.active_modal::<TestModal>(cx).is_some() {
 9609                        workspace.toggle_modal(window, cx, TestModal::new);
 9610                        workspace.toggle_modal(window, cx, TestModal::new);
 9611                    } else {
 9612                        workspace.toggle_modal(window, cx, TestModal::new);
 9613                    }
 9614                })
 9615            }
 9616        };
 9617
 9618        // If focus is transferred to another view that's not a panel or another pane, we still show
 9619        // the panel as zoomed.
 9620        focus_other_view(cx);
 9621        workspace.read_with(cx, |workspace, _| {
 9622            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9623            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9624        });
 9625
 9626        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9627        workspace.update_in(cx, |_workspace, window, cx| {
 9628            cx.focus_self(window);
 9629        });
 9630        workspace.read_with(cx, |workspace, _| {
 9631            assert_eq!(workspace.zoomed, None);
 9632            assert_eq!(workspace.zoomed_position, None);
 9633        });
 9634
 9635        // If focus is transferred again to another view that's not a panel or a pane, we won't
 9636        // show the panel as zoomed because it wasn't zoomed before.
 9637        focus_other_view(cx);
 9638        workspace.read_with(cx, |workspace, _| {
 9639            assert_eq!(workspace.zoomed, None);
 9640            assert_eq!(workspace.zoomed_position, None);
 9641        });
 9642
 9643        // When the panel is activated, it is zoomed again.
 9644        cx.dispatch_action(ToggleRightDock);
 9645        workspace.read_with(cx, |workspace, _| {
 9646            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9647            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9648        });
 9649
 9650        // Emitting a ZoomOut event unzooms the panel.
 9651        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
 9652        workspace.read_with(cx, |workspace, _| {
 9653            assert_eq!(workspace.zoomed, None);
 9654            assert_eq!(workspace.zoomed_position, None);
 9655        });
 9656
 9657        // Emit closed event on panel 1, which is active
 9658        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9659
 9660        // Now the left dock is closed, because panel_1 was the active panel
 9661        workspace.update(cx, |workspace, cx| {
 9662            let right_dock = workspace.right_dock();
 9663            assert!(!right_dock.read(cx).is_open());
 9664        });
 9665    }
 9666
 9667    #[gpui::test]
 9668    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
 9669        init_test(cx);
 9670
 9671        let fs = FakeFs::new(cx.background_executor.clone());
 9672        let project = Project::test(fs, [], cx).await;
 9673        let (workspace, cx) =
 9674            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9675        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9676
 9677        let dirty_regular_buffer = cx.new(|cx| {
 9678            TestItem::new(cx)
 9679                .with_dirty(true)
 9680                .with_label("1.txt")
 9681                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9682        });
 9683        let dirty_regular_buffer_2 = cx.new(|cx| {
 9684            TestItem::new(cx)
 9685                .with_dirty(true)
 9686                .with_label("2.txt")
 9687                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9688        });
 9689        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9690            TestItem::new(cx)
 9691                .with_dirty(true)
 9692                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9693                .with_label("Fake Project Search")
 9694                .with_project_items(&[
 9695                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9696                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9697                ])
 9698        });
 9699        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9700        workspace.update_in(cx, |workspace, window, cx| {
 9701            workspace.add_item(
 9702                pane.clone(),
 9703                Box::new(dirty_regular_buffer.clone()),
 9704                None,
 9705                false,
 9706                false,
 9707                window,
 9708                cx,
 9709            );
 9710            workspace.add_item(
 9711                pane.clone(),
 9712                Box::new(dirty_regular_buffer_2.clone()),
 9713                None,
 9714                false,
 9715                false,
 9716                window,
 9717                cx,
 9718            );
 9719            workspace.add_item(
 9720                pane.clone(),
 9721                Box::new(dirty_multi_buffer_with_both.clone()),
 9722                None,
 9723                false,
 9724                false,
 9725                window,
 9726                cx,
 9727            );
 9728        });
 9729
 9730        pane.update_in(cx, |pane, window, cx| {
 9731            pane.activate_item(2, true, true, window, cx);
 9732            assert_eq!(
 9733                pane.active_item().unwrap().item_id(),
 9734                multi_buffer_with_both_files_id,
 9735                "Should select the multi buffer in the pane"
 9736            );
 9737        });
 9738        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9739            pane.close_other_items(
 9740                &CloseOtherItems {
 9741                    save_intent: Some(SaveIntent::Save),
 9742                    close_pinned: true,
 9743                },
 9744                None,
 9745                window,
 9746                cx,
 9747            )
 9748        });
 9749        cx.background_executor.run_until_parked();
 9750        assert!(!cx.has_pending_prompt());
 9751        close_all_but_multi_buffer_task
 9752            .await
 9753            .expect("Closing all buffers but the multi buffer failed");
 9754        pane.update(cx, |pane, cx| {
 9755            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9756            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9757            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9758            assert_eq!(pane.items_len(), 1);
 9759            assert_eq!(
 9760                pane.active_item().unwrap().item_id(),
 9761                multi_buffer_with_both_files_id,
 9762                "Should have only the multi buffer left in the pane"
 9763            );
 9764            assert!(
 9765                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9766                "The multi buffer containing the unsaved buffer should still be dirty"
 9767            );
 9768        });
 9769
 9770        dirty_regular_buffer.update(cx, |buffer, cx| {
 9771            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9772        });
 9773
 9774        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9775            pane.close_active_item(
 9776                &CloseActiveItem {
 9777                    save_intent: Some(SaveIntent::Close),
 9778                    close_pinned: false,
 9779                },
 9780                window,
 9781                cx,
 9782            )
 9783        });
 9784        cx.background_executor.run_until_parked();
 9785        assert!(
 9786            cx.has_pending_prompt(),
 9787            "Dirty multi buffer should prompt a save dialog"
 9788        );
 9789        cx.simulate_prompt_answer("Save");
 9790        cx.background_executor.run_until_parked();
 9791        close_multi_buffer_task
 9792            .await
 9793            .expect("Closing the multi buffer failed");
 9794        pane.update(cx, |pane, cx| {
 9795            assert_eq!(
 9796                dirty_multi_buffer_with_both.read(cx).save_count,
 9797                1,
 9798                "Multi buffer item should get be saved"
 9799            );
 9800            // Test impl does not save inner items, so we do not assert them
 9801            assert_eq!(
 9802                pane.items_len(),
 9803                0,
 9804                "No more items should be left in the pane"
 9805            );
 9806            assert!(pane.active_item().is_none());
 9807        });
 9808    }
 9809
 9810    #[gpui::test]
 9811    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9812        cx: &mut TestAppContext,
 9813    ) {
 9814        init_test(cx);
 9815
 9816        let fs = FakeFs::new(cx.background_executor.clone());
 9817        let project = Project::test(fs, [], cx).await;
 9818        let (workspace, cx) =
 9819            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9820        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9821
 9822        let dirty_regular_buffer = cx.new(|cx| {
 9823            TestItem::new(cx)
 9824                .with_dirty(true)
 9825                .with_label("1.txt")
 9826                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9827        });
 9828        let dirty_regular_buffer_2 = cx.new(|cx| {
 9829            TestItem::new(cx)
 9830                .with_dirty(true)
 9831                .with_label("2.txt")
 9832                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9833        });
 9834        let clear_regular_buffer = cx.new(|cx| {
 9835            TestItem::new(cx)
 9836                .with_label("3.txt")
 9837                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9838        });
 9839
 9840        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9841            TestItem::new(cx)
 9842                .with_dirty(true)
 9843                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9844                .with_label("Fake Project Search")
 9845                .with_project_items(&[
 9846                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9847                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9848                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9849                ])
 9850        });
 9851        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9852        workspace.update_in(cx, |workspace, window, cx| {
 9853            workspace.add_item(
 9854                pane.clone(),
 9855                Box::new(dirty_regular_buffer.clone()),
 9856                None,
 9857                false,
 9858                false,
 9859                window,
 9860                cx,
 9861            );
 9862            workspace.add_item(
 9863                pane.clone(),
 9864                Box::new(dirty_multi_buffer_with_both.clone()),
 9865                None,
 9866                false,
 9867                false,
 9868                window,
 9869                cx,
 9870            );
 9871        });
 9872
 9873        pane.update_in(cx, |pane, window, cx| {
 9874            pane.activate_item(1, true, true, window, cx);
 9875            assert_eq!(
 9876                pane.active_item().unwrap().item_id(),
 9877                multi_buffer_with_both_files_id,
 9878                "Should select the multi buffer in the pane"
 9879            );
 9880        });
 9881        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9882            pane.close_active_item(
 9883                &CloseActiveItem {
 9884                    save_intent: None,
 9885                    close_pinned: false,
 9886                },
 9887                window,
 9888                cx,
 9889            )
 9890        });
 9891        cx.background_executor.run_until_parked();
 9892        assert!(
 9893            cx.has_pending_prompt(),
 9894            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9895        );
 9896    }
 9897
 9898    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9899    /// closed when they are deleted from disk.
 9900    #[gpui::test]
 9901    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9902        init_test(cx);
 9903
 9904        // Enable the close_on_disk_deletion setting
 9905        cx.update_global(|store: &mut SettingsStore, cx| {
 9906            store.update_user_settings(cx, |settings| {
 9907                settings.workspace.close_on_file_delete = Some(true);
 9908            });
 9909        });
 9910
 9911        let fs = FakeFs::new(cx.background_executor.clone());
 9912        let project = Project::test(fs, [], cx).await;
 9913        let (workspace, cx) =
 9914            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9915        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9916
 9917        // Create a test item that simulates a file
 9918        let item = cx.new(|cx| {
 9919            TestItem::new(cx)
 9920                .with_label("test.txt")
 9921                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9922        });
 9923
 9924        // Add item to workspace
 9925        workspace.update_in(cx, |workspace, window, cx| {
 9926            workspace.add_item(
 9927                pane.clone(),
 9928                Box::new(item.clone()),
 9929                None,
 9930                false,
 9931                false,
 9932                window,
 9933                cx,
 9934            );
 9935        });
 9936
 9937        // Verify the item is in the pane
 9938        pane.read_with(cx, |pane, _| {
 9939            assert_eq!(pane.items().count(), 1);
 9940        });
 9941
 9942        // Simulate file deletion by setting the item's deleted state
 9943        item.update(cx, |item, _| {
 9944            item.set_has_deleted_file(true);
 9945        });
 9946
 9947        // Emit UpdateTab event to trigger the close behavior
 9948        cx.run_until_parked();
 9949        item.update(cx, |_, cx| {
 9950            cx.emit(ItemEvent::UpdateTab);
 9951        });
 9952
 9953        // Allow the close operation to complete
 9954        cx.run_until_parked();
 9955
 9956        // Verify the item was automatically closed
 9957        pane.read_with(cx, |pane, _| {
 9958            assert_eq!(
 9959                pane.items().count(),
 9960                0,
 9961                "Item should be automatically closed when file is deleted"
 9962            );
 9963        });
 9964    }
 9965
 9966    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9967    /// open with a strikethrough when they are deleted from disk.
 9968    #[gpui::test]
 9969    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9970        init_test(cx);
 9971
 9972        // Ensure close_on_disk_deletion is disabled (default)
 9973        cx.update_global(|store: &mut SettingsStore, cx| {
 9974            store.update_user_settings(cx, |settings| {
 9975                settings.workspace.close_on_file_delete = Some(false);
 9976            });
 9977        });
 9978
 9979        let fs = FakeFs::new(cx.background_executor.clone());
 9980        let project = Project::test(fs, [], cx).await;
 9981        let (workspace, cx) =
 9982            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9983        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9984
 9985        // Create a test item that simulates a file
 9986        let item = cx.new(|cx| {
 9987            TestItem::new(cx)
 9988                .with_label("test.txt")
 9989                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9990        });
 9991
 9992        // Add item to workspace
 9993        workspace.update_in(cx, |workspace, window, cx| {
 9994            workspace.add_item(
 9995                pane.clone(),
 9996                Box::new(item.clone()),
 9997                None,
 9998                false,
 9999                false,
10000                window,
10001                cx,
10002            );
10003        });
10004
10005        // Verify the item is in the pane
10006        pane.read_with(cx, |pane, _| {
10007            assert_eq!(pane.items().count(), 1);
10008        });
10009
10010        // Simulate file deletion
10011        item.update(cx, |item, _| {
10012            item.set_has_deleted_file(true);
10013        });
10014
10015        // Emit UpdateTab event
10016        cx.run_until_parked();
10017        item.update(cx, |_, cx| {
10018            cx.emit(ItemEvent::UpdateTab);
10019        });
10020
10021        // Allow any potential close operation to complete
10022        cx.run_until_parked();
10023
10024        // Verify the item remains open (with strikethrough)
10025        pane.read_with(cx, |pane, _| {
10026            assert_eq!(
10027                pane.items().count(),
10028                1,
10029                "Item should remain open when close_on_disk_deletion is disabled"
10030            );
10031        });
10032
10033        // Verify the item shows as deleted
10034        item.read_with(cx, |item, _| {
10035            assert!(
10036                item.has_deleted_file,
10037                "Item should be marked as having deleted file"
10038            );
10039        });
10040    }
10041
10042    /// Tests that dirty files are not automatically closed when deleted from disk,
10043    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10044    /// unsaved changes without being prompted.
10045    #[gpui::test]
10046    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10047        init_test(cx);
10048
10049        // Enable the close_on_file_delete setting
10050        cx.update_global(|store: &mut SettingsStore, cx| {
10051            store.update_user_settings(cx, |settings| {
10052                settings.workspace.close_on_file_delete = Some(true);
10053            });
10054        });
10055
10056        let fs = FakeFs::new(cx.background_executor.clone());
10057        let project = Project::test(fs, [], cx).await;
10058        let (workspace, cx) =
10059            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10060        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10061
10062        // Create a dirty test item
10063        let item = cx.new(|cx| {
10064            TestItem::new(cx)
10065                .with_dirty(true)
10066                .with_label("test.txt")
10067                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10068        });
10069
10070        // Add item to workspace
10071        workspace.update_in(cx, |workspace, window, cx| {
10072            workspace.add_item(
10073                pane.clone(),
10074                Box::new(item.clone()),
10075                None,
10076                false,
10077                false,
10078                window,
10079                cx,
10080            );
10081        });
10082
10083        // Simulate file deletion
10084        item.update(cx, |item, _| {
10085            item.set_has_deleted_file(true);
10086        });
10087
10088        // Emit UpdateTab event to trigger the close behavior
10089        cx.run_until_parked();
10090        item.update(cx, |_, cx| {
10091            cx.emit(ItemEvent::UpdateTab);
10092        });
10093
10094        // Allow any potential close operation to complete
10095        cx.run_until_parked();
10096
10097        // Verify the item remains open (dirty files are not auto-closed)
10098        pane.read_with(cx, |pane, _| {
10099            assert_eq!(
10100                pane.items().count(),
10101                1,
10102                "Dirty items should not be automatically closed even when file is deleted"
10103            );
10104        });
10105
10106        // Verify the item is marked as deleted and still dirty
10107        item.read_with(cx, |item, _| {
10108            assert!(
10109                item.has_deleted_file,
10110                "Item should be marked as having deleted file"
10111            );
10112            assert!(item.is_dirty, "Item should still be dirty");
10113        });
10114    }
10115
10116    /// Tests that navigation history is cleaned up when files are auto-closed
10117    /// due to deletion from disk.
10118    #[gpui::test]
10119    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10120        init_test(cx);
10121
10122        // Enable the close_on_file_delete setting
10123        cx.update_global(|store: &mut SettingsStore, cx| {
10124            store.update_user_settings(cx, |settings| {
10125                settings.workspace.close_on_file_delete = Some(true);
10126            });
10127        });
10128
10129        let fs = FakeFs::new(cx.background_executor.clone());
10130        let project = Project::test(fs, [], cx).await;
10131        let (workspace, cx) =
10132            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10133        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10134
10135        // Create test items
10136        let item1 = cx.new(|cx| {
10137            TestItem::new(cx)
10138                .with_label("test1.txt")
10139                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10140        });
10141        let item1_id = item1.item_id();
10142
10143        let item2 = cx.new(|cx| {
10144            TestItem::new(cx)
10145                .with_label("test2.txt")
10146                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10147        });
10148
10149        // Add items to workspace
10150        workspace.update_in(cx, |workspace, window, cx| {
10151            workspace.add_item(
10152                pane.clone(),
10153                Box::new(item1.clone()),
10154                None,
10155                false,
10156                false,
10157                window,
10158                cx,
10159            );
10160            workspace.add_item(
10161                pane.clone(),
10162                Box::new(item2.clone()),
10163                None,
10164                false,
10165                false,
10166                window,
10167                cx,
10168            );
10169        });
10170
10171        // Activate item1 to ensure it gets navigation entries
10172        pane.update_in(cx, |pane, window, cx| {
10173            pane.activate_item(0, true, true, window, cx);
10174        });
10175
10176        // Switch to item2 and back to create navigation history
10177        pane.update_in(cx, |pane, window, cx| {
10178            pane.activate_item(1, true, true, window, cx);
10179        });
10180        cx.run_until_parked();
10181
10182        pane.update_in(cx, |pane, window, cx| {
10183            pane.activate_item(0, true, true, window, cx);
10184        });
10185        cx.run_until_parked();
10186
10187        // Simulate file deletion for item1
10188        item1.update(cx, |item, _| {
10189            item.set_has_deleted_file(true);
10190        });
10191
10192        // Emit UpdateTab event to trigger the close behavior
10193        item1.update(cx, |_, cx| {
10194            cx.emit(ItemEvent::UpdateTab);
10195        });
10196        cx.run_until_parked();
10197
10198        // Verify item1 was closed
10199        pane.read_with(cx, |pane, _| {
10200            assert_eq!(
10201                pane.items().count(),
10202                1,
10203                "Should have 1 item remaining after auto-close"
10204            );
10205        });
10206
10207        // Check navigation history after close
10208        let has_item = pane.read_with(cx, |pane, cx| {
10209            let mut has_item = false;
10210            pane.nav_history().for_each_entry(cx, |entry, _| {
10211                if entry.item.id() == item1_id {
10212                    has_item = true;
10213                }
10214            });
10215            has_item
10216        });
10217
10218        assert!(
10219            !has_item,
10220            "Navigation history should not contain closed item entries"
10221        );
10222    }
10223
10224    #[gpui::test]
10225    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10226        cx: &mut TestAppContext,
10227    ) {
10228        init_test(cx);
10229
10230        let fs = FakeFs::new(cx.background_executor.clone());
10231        let project = Project::test(fs, [], cx).await;
10232        let (workspace, cx) =
10233            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10234        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10235
10236        let dirty_regular_buffer = cx.new(|cx| {
10237            TestItem::new(cx)
10238                .with_dirty(true)
10239                .with_label("1.txt")
10240                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10241        });
10242        let dirty_regular_buffer_2 = cx.new(|cx| {
10243            TestItem::new(cx)
10244                .with_dirty(true)
10245                .with_label("2.txt")
10246                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10247        });
10248        let clear_regular_buffer = cx.new(|cx| {
10249            TestItem::new(cx)
10250                .with_label("3.txt")
10251                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10252        });
10253
10254        let dirty_multi_buffer = cx.new(|cx| {
10255            TestItem::new(cx)
10256                .with_dirty(true)
10257                .with_buffer_kind(ItemBufferKind::Multibuffer)
10258                .with_label("Fake Project Search")
10259                .with_project_items(&[
10260                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10261                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10262                    clear_regular_buffer.read(cx).project_items[0].clone(),
10263                ])
10264        });
10265        workspace.update_in(cx, |workspace, window, cx| {
10266            workspace.add_item(
10267                pane.clone(),
10268                Box::new(dirty_regular_buffer.clone()),
10269                None,
10270                false,
10271                false,
10272                window,
10273                cx,
10274            );
10275            workspace.add_item(
10276                pane.clone(),
10277                Box::new(dirty_regular_buffer_2.clone()),
10278                None,
10279                false,
10280                false,
10281                window,
10282                cx,
10283            );
10284            workspace.add_item(
10285                pane.clone(),
10286                Box::new(dirty_multi_buffer.clone()),
10287                None,
10288                false,
10289                false,
10290                window,
10291                cx,
10292            );
10293        });
10294
10295        pane.update_in(cx, |pane, window, cx| {
10296            pane.activate_item(2, true, true, window, cx);
10297            assert_eq!(
10298                pane.active_item().unwrap().item_id(),
10299                dirty_multi_buffer.item_id(),
10300                "Should select the multi buffer in the pane"
10301            );
10302        });
10303        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10304            pane.close_active_item(
10305                &CloseActiveItem {
10306                    save_intent: None,
10307                    close_pinned: false,
10308                },
10309                window,
10310                cx,
10311            )
10312        });
10313        cx.background_executor.run_until_parked();
10314        assert!(
10315            !cx.has_pending_prompt(),
10316            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10317        );
10318        close_multi_buffer_task
10319            .await
10320            .expect("Closing multi buffer failed");
10321        pane.update(cx, |pane, cx| {
10322            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10323            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10324            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10325            assert_eq!(
10326                pane.items()
10327                    .map(|item| item.item_id())
10328                    .sorted()
10329                    .collect::<Vec<_>>(),
10330                vec![
10331                    dirty_regular_buffer.item_id(),
10332                    dirty_regular_buffer_2.item_id(),
10333                ],
10334                "Should have no multi buffer left in the pane"
10335            );
10336            assert!(dirty_regular_buffer.read(cx).is_dirty);
10337            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10338        });
10339    }
10340
10341    #[gpui::test]
10342    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10343        init_test(cx);
10344        let fs = FakeFs::new(cx.executor());
10345        let project = Project::test(fs, [], cx).await;
10346        let (workspace, cx) =
10347            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10348
10349        // Add a new panel to the right dock, opening the dock and setting the
10350        // focus to the new panel.
10351        let panel = workspace.update_in(cx, |workspace, window, cx| {
10352            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10353            workspace.add_panel(panel.clone(), window, cx);
10354
10355            workspace
10356                .right_dock()
10357                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10358
10359            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10360
10361            panel
10362        });
10363
10364        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10365        // panel to the next valid position which, in this case, is the left
10366        // dock.
10367        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10368        workspace.update(cx, |workspace, cx| {
10369            assert!(workspace.left_dock().read(cx).is_open());
10370            assert_eq!(panel.read(cx).position, DockPosition::Left);
10371        });
10372
10373        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10374        // panel to the next valid position which, in this case, is the bottom
10375        // dock.
10376        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10377        workspace.update(cx, |workspace, cx| {
10378            assert!(workspace.bottom_dock().read(cx).is_open());
10379            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10380        });
10381
10382        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10383        // around moving the panel to its initial position, the right dock.
10384        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10385        workspace.update(cx, |workspace, cx| {
10386            assert!(workspace.right_dock().read(cx).is_open());
10387            assert_eq!(panel.read(cx).position, DockPosition::Right);
10388        });
10389
10390        // Remove focus from the panel, ensuring that, if the panel is not
10391        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10392        // the panel's position, so the panel is still in the right dock.
10393        workspace.update_in(cx, |workspace, window, cx| {
10394            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10395        });
10396
10397        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10398        workspace.update(cx, |workspace, cx| {
10399            assert!(workspace.right_dock().read(cx).is_open());
10400            assert_eq!(panel.read(cx).position, DockPosition::Right);
10401        });
10402    }
10403
10404    #[gpui::test]
10405    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10406        init_test(cx);
10407
10408        let fs = FakeFs::new(cx.executor());
10409        let project = Project::test(fs, [], cx).await;
10410        let (workspace, cx) =
10411            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10412
10413        let item_1 = cx.new(|cx| {
10414            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10415        });
10416        workspace.update_in(cx, |workspace, window, cx| {
10417            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10418            workspace.move_item_to_pane_in_direction(
10419                &MoveItemToPaneInDirection {
10420                    direction: SplitDirection::Right,
10421                    focus: true,
10422                    clone: false,
10423                },
10424                window,
10425                cx,
10426            );
10427            workspace.move_item_to_pane_at_index(
10428                &MoveItemToPane {
10429                    destination: 3,
10430                    focus: true,
10431                    clone: false,
10432                },
10433                window,
10434                cx,
10435            );
10436
10437            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10438            assert_eq!(
10439                pane_items_paths(&workspace.active_pane, cx),
10440                vec!["first.txt".to_string()],
10441                "Single item was not moved anywhere"
10442            );
10443        });
10444
10445        let item_2 = cx.new(|cx| {
10446            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10447        });
10448        workspace.update_in(cx, |workspace, window, cx| {
10449            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10450            assert_eq!(
10451                pane_items_paths(&workspace.panes[0], cx),
10452                vec!["first.txt".to_string(), "second.txt".to_string()],
10453            );
10454            workspace.move_item_to_pane_in_direction(
10455                &MoveItemToPaneInDirection {
10456                    direction: SplitDirection::Right,
10457                    focus: true,
10458                    clone: false,
10459                },
10460                window,
10461                cx,
10462            );
10463
10464            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10465            assert_eq!(
10466                pane_items_paths(&workspace.panes[0], cx),
10467                vec!["first.txt".to_string()],
10468                "After moving, one item should be left in the original pane"
10469            );
10470            assert_eq!(
10471                pane_items_paths(&workspace.panes[1], cx),
10472                vec!["second.txt".to_string()],
10473                "New item should have been moved to the new pane"
10474            );
10475        });
10476
10477        let item_3 = cx.new(|cx| {
10478            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10479        });
10480        workspace.update_in(cx, |workspace, window, cx| {
10481            let original_pane = workspace.panes[0].clone();
10482            workspace.set_active_pane(&original_pane, window, cx);
10483            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10484            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10485            assert_eq!(
10486                pane_items_paths(&workspace.active_pane, cx),
10487                vec!["first.txt".to_string(), "third.txt".to_string()],
10488                "New pane should be ready to move one item out"
10489            );
10490
10491            workspace.move_item_to_pane_at_index(
10492                &MoveItemToPane {
10493                    destination: 3,
10494                    focus: true,
10495                    clone: false,
10496                },
10497                window,
10498                cx,
10499            );
10500            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10501            assert_eq!(
10502                pane_items_paths(&workspace.active_pane, cx),
10503                vec!["first.txt".to_string()],
10504                "After moving, one item should be left in the original pane"
10505            );
10506            assert_eq!(
10507                pane_items_paths(&workspace.panes[1], cx),
10508                vec!["second.txt".to_string()],
10509                "Previously created pane should be unchanged"
10510            );
10511            assert_eq!(
10512                pane_items_paths(&workspace.panes[2], cx),
10513                vec!["third.txt".to_string()],
10514                "New item should have been moved to the new pane"
10515            );
10516        });
10517    }
10518
10519    #[gpui::test]
10520    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10521        init_test(cx);
10522
10523        let fs = FakeFs::new(cx.executor());
10524        let project = Project::test(fs, [], cx).await;
10525        let (workspace, cx) =
10526            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10527
10528        let item_1 = cx.new(|cx| {
10529            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10530        });
10531        workspace.update_in(cx, |workspace, window, cx| {
10532            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10533            workspace.move_item_to_pane_in_direction(
10534                &MoveItemToPaneInDirection {
10535                    direction: SplitDirection::Right,
10536                    focus: true,
10537                    clone: true,
10538                },
10539                window,
10540                cx,
10541            );
10542            workspace.move_item_to_pane_at_index(
10543                &MoveItemToPane {
10544                    destination: 3,
10545                    focus: true,
10546                    clone: true,
10547                },
10548                window,
10549                cx,
10550            );
10551        });
10552        cx.run_until_parked();
10553
10554        workspace.update(cx, |workspace, cx| {
10555            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10556            for pane in workspace.panes() {
10557                assert_eq!(
10558                    pane_items_paths(pane, cx),
10559                    vec!["first.txt".to_string()],
10560                    "Single item exists in all panes"
10561                );
10562            }
10563        });
10564
10565        // verify that the active pane has been updated after waiting for the
10566        // pane focus event to fire and resolve
10567        workspace.read_with(cx, |workspace, _app| {
10568            assert_eq!(
10569                workspace.active_pane(),
10570                &workspace.panes[2],
10571                "The third pane should be the active one: {:?}",
10572                workspace.panes
10573            );
10574        })
10575    }
10576
10577    mod register_project_item_tests {
10578
10579        use super::*;
10580
10581        // View
10582        struct TestPngItemView {
10583            focus_handle: FocusHandle,
10584        }
10585        // Model
10586        struct TestPngItem {}
10587
10588        impl project::ProjectItem for TestPngItem {
10589            fn try_open(
10590                _project: &Entity<Project>,
10591                path: &ProjectPath,
10592                cx: &mut App,
10593            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10594                if path.path.extension().unwrap() == "png" {
10595                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10596                } else {
10597                    None
10598                }
10599            }
10600
10601            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10602                None
10603            }
10604
10605            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10606                None
10607            }
10608
10609            fn is_dirty(&self) -> bool {
10610                false
10611            }
10612        }
10613
10614        impl Item for TestPngItemView {
10615            type Event = ();
10616            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10617                "".into()
10618            }
10619        }
10620        impl EventEmitter<()> for TestPngItemView {}
10621        impl Focusable for TestPngItemView {
10622            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10623                self.focus_handle.clone()
10624            }
10625        }
10626
10627        impl Render for TestPngItemView {
10628            fn render(
10629                &mut self,
10630                _window: &mut Window,
10631                _cx: &mut Context<Self>,
10632            ) -> impl IntoElement {
10633                Empty
10634            }
10635        }
10636
10637        impl ProjectItem for TestPngItemView {
10638            type Item = TestPngItem;
10639
10640            fn for_project_item(
10641                _project: Entity<Project>,
10642                _pane: Option<&Pane>,
10643                _item: Entity<Self::Item>,
10644                _: &mut Window,
10645                cx: &mut Context<Self>,
10646            ) -> Self
10647            where
10648                Self: Sized,
10649            {
10650                Self {
10651                    focus_handle: cx.focus_handle(),
10652                }
10653            }
10654        }
10655
10656        // View
10657        struct TestIpynbItemView {
10658            focus_handle: FocusHandle,
10659        }
10660        // Model
10661        struct TestIpynbItem {}
10662
10663        impl project::ProjectItem for TestIpynbItem {
10664            fn try_open(
10665                _project: &Entity<Project>,
10666                path: &ProjectPath,
10667                cx: &mut App,
10668            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10669                if path.path.extension().unwrap() == "ipynb" {
10670                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10671                } else {
10672                    None
10673                }
10674            }
10675
10676            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10677                None
10678            }
10679
10680            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10681                None
10682            }
10683
10684            fn is_dirty(&self) -> bool {
10685                false
10686            }
10687        }
10688
10689        impl Item for TestIpynbItemView {
10690            type Event = ();
10691            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10692                "".into()
10693            }
10694        }
10695        impl EventEmitter<()> for TestIpynbItemView {}
10696        impl Focusable for TestIpynbItemView {
10697            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10698                self.focus_handle.clone()
10699            }
10700        }
10701
10702        impl Render for TestIpynbItemView {
10703            fn render(
10704                &mut self,
10705                _window: &mut Window,
10706                _cx: &mut Context<Self>,
10707            ) -> impl IntoElement {
10708                Empty
10709            }
10710        }
10711
10712        impl ProjectItem for TestIpynbItemView {
10713            type Item = TestIpynbItem;
10714
10715            fn for_project_item(
10716                _project: Entity<Project>,
10717                _pane: Option<&Pane>,
10718                _item: Entity<Self::Item>,
10719                _: &mut Window,
10720                cx: &mut Context<Self>,
10721            ) -> Self
10722            where
10723                Self: Sized,
10724            {
10725                Self {
10726                    focus_handle: cx.focus_handle(),
10727                }
10728            }
10729        }
10730
10731        struct TestAlternatePngItemView {
10732            focus_handle: FocusHandle,
10733        }
10734
10735        impl Item for TestAlternatePngItemView {
10736            type Event = ();
10737            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10738                "".into()
10739            }
10740        }
10741
10742        impl EventEmitter<()> for TestAlternatePngItemView {}
10743        impl Focusable for TestAlternatePngItemView {
10744            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10745                self.focus_handle.clone()
10746            }
10747        }
10748
10749        impl Render for TestAlternatePngItemView {
10750            fn render(
10751                &mut self,
10752                _window: &mut Window,
10753                _cx: &mut Context<Self>,
10754            ) -> impl IntoElement {
10755                Empty
10756            }
10757        }
10758
10759        impl ProjectItem for TestAlternatePngItemView {
10760            type Item = TestPngItem;
10761
10762            fn for_project_item(
10763                _project: Entity<Project>,
10764                _pane: Option<&Pane>,
10765                _item: Entity<Self::Item>,
10766                _: &mut Window,
10767                cx: &mut Context<Self>,
10768            ) -> Self
10769            where
10770                Self: Sized,
10771            {
10772                Self {
10773                    focus_handle: cx.focus_handle(),
10774                }
10775            }
10776        }
10777
10778        #[gpui::test]
10779        async fn test_register_project_item(cx: &mut TestAppContext) {
10780            init_test(cx);
10781
10782            cx.update(|cx| {
10783                register_project_item::<TestPngItemView>(cx);
10784                register_project_item::<TestIpynbItemView>(cx);
10785            });
10786
10787            let fs = FakeFs::new(cx.executor());
10788            fs.insert_tree(
10789                "/root1",
10790                json!({
10791                    "one.png": "BINARYDATAHERE",
10792                    "two.ipynb": "{ totally a notebook }",
10793                    "three.txt": "editing text, sure why not?"
10794                }),
10795            )
10796            .await;
10797
10798            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10799            let (workspace, cx) =
10800                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10801
10802            let worktree_id = project.update(cx, |project, cx| {
10803                project.worktrees(cx).next().unwrap().read(cx).id()
10804            });
10805
10806            let handle = workspace
10807                .update_in(cx, |workspace, window, cx| {
10808                    let project_path = (worktree_id, rel_path("one.png"));
10809                    workspace.open_path(project_path, None, true, window, cx)
10810                })
10811                .await
10812                .unwrap();
10813
10814            // Now we can check if the handle we got back errored or not
10815            assert_eq!(
10816                handle.to_any().entity_type(),
10817                TypeId::of::<TestPngItemView>()
10818            );
10819
10820            let handle = workspace
10821                .update_in(cx, |workspace, window, cx| {
10822                    let project_path = (worktree_id, rel_path("two.ipynb"));
10823                    workspace.open_path(project_path, None, true, window, cx)
10824                })
10825                .await
10826                .unwrap();
10827
10828            assert_eq!(
10829                handle.to_any().entity_type(),
10830                TypeId::of::<TestIpynbItemView>()
10831            );
10832
10833            let handle = workspace
10834                .update_in(cx, |workspace, window, cx| {
10835                    let project_path = (worktree_id, rel_path("three.txt"));
10836                    workspace.open_path(project_path, None, true, window, cx)
10837                })
10838                .await;
10839            assert!(handle.is_err());
10840        }
10841
10842        #[gpui::test]
10843        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10844            init_test(cx);
10845
10846            cx.update(|cx| {
10847                register_project_item::<TestPngItemView>(cx);
10848                register_project_item::<TestAlternatePngItemView>(cx);
10849            });
10850
10851            let fs = FakeFs::new(cx.executor());
10852            fs.insert_tree(
10853                "/root1",
10854                json!({
10855                    "one.png": "BINARYDATAHERE",
10856                    "two.ipynb": "{ totally a notebook }",
10857                    "three.txt": "editing text, sure why not?"
10858                }),
10859            )
10860            .await;
10861            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10862            let (workspace, cx) =
10863                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10864            let worktree_id = project.update(cx, |project, cx| {
10865                project.worktrees(cx).next().unwrap().read(cx).id()
10866            });
10867
10868            let handle = workspace
10869                .update_in(cx, |workspace, window, cx| {
10870                    let project_path = (worktree_id, rel_path("one.png"));
10871                    workspace.open_path(project_path, None, true, window, cx)
10872                })
10873                .await
10874                .unwrap();
10875
10876            // This _must_ be the second item registered
10877            assert_eq!(
10878                handle.to_any().entity_type(),
10879                TypeId::of::<TestAlternatePngItemView>()
10880            );
10881
10882            let handle = workspace
10883                .update_in(cx, |workspace, window, cx| {
10884                    let project_path = (worktree_id, rel_path("three.txt"));
10885                    workspace.open_path(project_path, None, true, window, cx)
10886                })
10887                .await;
10888            assert!(handle.is_err());
10889        }
10890    }
10891
10892    #[gpui::test]
10893    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
10894        init_test(cx);
10895
10896        let fs = FakeFs::new(cx.executor());
10897        let project = Project::test(fs, [], cx).await;
10898        let (workspace, _cx) =
10899            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10900
10901        // Test with status bar shown (default)
10902        workspace.read_with(cx, |workspace, cx| {
10903            let visible = workspace.status_bar_visible(cx);
10904            assert!(visible, "Status bar should be visible by default");
10905        });
10906
10907        // Test with status bar hidden
10908        cx.update_global(|store: &mut SettingsStore, cx| {
10909            store.update_user_settings(cx, |settings| {
10910                settings.status_bar.get_or_insert_default().show = Some(false);
10911            });
10912        });
10913
10914        workspace.read_with(cx, |workspace, cx| {
10915            let visible = workspace.status_bar_visible(cx);
10916            assert!(!visible, "Status bar should be hidden when show is false");
10917        });
10918
10919        // Test with status bar shown explicitly
10920        cx.update_global(|store: &mut SettingsStore, cx| {
10921            store.update_user_settings(cx, |settings| {
10922                settings.status_bar.get_or_insert_default().show = Some(true);
10923            });
10924        });
10925
10926        workspace.read_with(cx, |workspace, cx| {
10927            let visible = workspace.status_bar_visible(cx);
10928            assert!(visible, "Status bar should be visible when show is true");
10929        });
10930    }
10931
10932    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10933        pane.read(cx)
10934            .items()
10935            .flat_map(|item| {
10936                item.project_paths(cx)
10937                    .into_iter()
10938                    .map(|path| path.path.display(PathStyle::local()).into_owned())
10939            })
10940            .collect()
10941    }
10942
10943    pub fn init_test(cx: &mut TestAppContext) {
10944        cx.update(|cx| {
10945            let settings_store = SettingsStore::test(cx);
10946            cx.set_global(settings_store);
10947            theme::init(theme::LoadThemes::JustBase, cx);
10948            language::init(cx);
10949            crate::init_settings(cx);
10950            Project::init_settings(cx);
10951        });
10952    }
10953
10954    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10955        let item = TestProjectItem::new(id, path, cx);
10956        item.update(cx, |item, _| {
10957            item.is_dirty = true;
10958        });
10959        item
10960    }
10961}