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