workspace.rs

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