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