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