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