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