workspace.rs

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