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