workspace.rs

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