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