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