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