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