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 encodings::Encoding;
   23
   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 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<Encoding>,
  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 encoding = encoding.unwrap_or_default();
  653
  654                project.update(cx, |project, _| {project.encoding_options.encoding.lock().unwrap().set(encoding.get())});
  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<Encoding>,
  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        self.encoding_options.reset();
 1949
 1950        let to_load = if let Some(pane) = pane.upgrade() {
 1951            pane.update(cx, |pane, cx| {
 1952                window.focus(&pane.focus_handle(cx));
 1953                loop {
 1954                    // Retrieve the weak item handle from the history.
 1955                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 1956
 1957                    // If the item is still present in this pane, then activate it.
 1958                    if let Some(index) = entry
 1959                        .item
 1960                        .upgrade()
 1961                        .and_then(|v| pane.index_for_item(v.as_ref()))
 1962                    {
 1963                        let prev_active_item_index = pane.active_item_index();
 1964                        pane.nav_history_mut().set_mode(mode);
 1965                        pane.activate_item(index, true, true, window, cx);
 1966                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1967
 1968                        let mut navigated = prev_active_item_index != pane.active_item_index();
 1969                        if let Some(data) = entry.data {
 1970                            navigated |= pane.active_item()?.navigate(data, window, cx);
 1971                        }
 1972
 1973                        if navigated {
 1974                            break None;
 1975                        }
 1976                    } else {
 1977                        // If the item is no longer present in this pane, then retrieve its
 1978                        // path info in order to reopen it.
 1979                        break pane
 1980                            .nav_history()
 1981                            .path_for_item(entry.item.id())
 1982                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 1983                    }
 1984                }
 1985            })
 1986        } else {
 1987            None
 1988        };
 1989
 1990        if let Some((project_path, abs_path, entry)) = to_load {
 1991            // If the item was no longer present, then load it again from its previous path, first try the local path
 1992            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 1993
 1994            cx.spawn_in(window, async move  |workspace, cx| {
 1995                let open_by_project_path = open_by_project_path.await;
 1996                let mut navigated = false;
 1997                match open_by_project_path
 1998                    .with_context(|| format!("Navigating to {project_path:?}"))
 1999                {
 2000                    Ok((project_entry_id, build_item)) => {
 2001                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2002                            pane.nav_history_mut().set_mode(mode);
 2003                            pane.active_item().map(|p| p.item_id())
 2004                        })?;
 2005
 2006                        pane.update_in(cx, |pane, window, cx| {
 2007                            let item = pane.open_item(
 2008                                project_entry_id,
 2009                                project_path,
 2010                                true,
 2011                                entry.is_preview,
 2012                                true,
 2013                                None,
 2014                                window, cx,
 2015                                build_item,
 2016                            );
 2017                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2018                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2019                            if let Some(data) = entry.data {
 2020                                navigated |= item.navigate(data, window, cx);
 2021                            }
 2022                        })?;
 2023                    }
 2024                    Err(open_by_project_path_e) => {
 2025                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2026                        // and its worktree is now dropped
 2027                        if let Some(abs_path) = abs_path {
 2028                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2029                                pane.nav_history_mut().set_mode(mode);
 2030                                pane.active_item().map(|p| p.item_id())
 2031                            })?;
 2032                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2033                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2034                            })?;
 2035                            match open_by_abs_path
 2036                                .await
 2037                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2038                            {
 2039                                Ok(item) => {
 2040                                    pane.update_in(cx, |pane, window, cx| {
 2041                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2042                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2043                                        if let Some(data) = entry.data {
 2044                                            navigated |= item.navigate(data, window, cx);
 2045                                        }
 2046                                    })?;
 2047                                }
 2048                                Err(open_by_abs_path_e) => {
 2049                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2050                                }
 2051                            }
 2052                        }
 2053                    }
 2054                }
 2055
 2056                if !navigated {
 2057                    workspace
 2058                        .update_in(cx, |workspace, window, cx| {
 2059                            Self::navigate_history(workspace, pane, mode, window, cx)
 2060                        })?
 2061                        .await?;
 2062                }
 2063
 2064                Ok(())
 2065            })
 2066        } else {
 2067            Task::ready(Ok(()))
 2068        }
 2069    }
 2070
 2071    pub fn go_back(
 2072        &mut self,
 2073        pane: WeakEntity<Pane>,
 2074        window: &mut Window,
 2075        cx: &mut Context<Workspace>,
 2076    ) -> Task<Result<()>> {
 2077        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2078    }
 2079
 2080    pub fn go_forward(
 2081        &mut self,
 2082        pane: WeakEntity<Pane>,
 2083        window: &mut Window,
 2084        cx: &mut Context<Workspace>,
 2085    ) -> Task<Result<()>> {
 2086        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2087    }
 2088
 2089    pub fn reopen_closed_item(
 2090        &mut self,
 2091        window: &mut Window,
 2092        cx: &mut Context<Workspace>,
 2093    ) -> Task<Result<()>> {
 2094        self.navigate_history(
 2095            self.active_pane().downgrade(),
 2096            NavigationMode::ReopeningClosedItem,
 2097            window,
 2098            cx,
 2099        )
 2100    }
 2101
 2102    pub fn client(&self) -> &Arc<Client> {
 2103        &self.app_state.client
 2104    }
 2105
 2106    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2107        self.titlebar_item = Some(item);
 2108        cx.notify();
 2109    }
 2110
 2111    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2112        self.on_prompt_for_new_path = Some(prompt)
 2113    }
 2114
 2115    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2116        self.on_prompt_for_open_path = Some(prompt)
 2117    }
 2118
 2119    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2120        self.terminal_provider = Some(Box::new(provider));
 2121    }
 2122
 2123    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2124        self.debugger_provider = Some(Arc::new(provider));
 2125    }
 2126
 2127    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2128        self.debugger_provider.clone()
 2129    }
 2130
 2131    pub fn prompt_for_open_path(
 2132        &mut self,
 2133        path_prompt_options: PathPromptOptions,
 2134        lister: DirectoryLister,
 2135        window: &mut Window,
 2136        cx: &mut Context<Self>,
 2137    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2138        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2139            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2140            let rx = prompt(self, lister, window, cx);
 2141            self.on_prompt_for_open_path = Some(prompt);
 2142            rx
 2143        } else {
 2144            let (tx, rx) = oneshot::channel();
 2145            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2146
 2147            cx.spawn_in(window, async move |workspace, cx| {
 2148                let Ok(result) = abs_path.await else {
 2149                    return Ok(());
 2150                };
 2151
 2152                match result {
 2153                    Ok(result) => {
 2154                        tx.send(result).ok();
 2155                    }
 2156                    Err(err) => {
 2157                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2158                            workspace.show_portal_error(err.to_string(), cx);
 2159                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2160                            let rx = prompt(workspace, lister, window, cx);
 2161                            workspace.on_prompt_for_open_path = Some(prompt);
 2162                            rx
 2163                        })?;
 2164                        if let Ok(path) = rx.await {
 2165                            tx.send(path).ok();
 2166                        }
 2167                    }
 2168                };
 2169                anyhow::Ok(())
 2170            })
 2171            .detach();
 2172
 2173            rx
 2174        }
 2175    }
 2176
 2177    pub fn prompt_for_new_path(
 2178        &mut self,
 2179        lister: DirectoryLister,
 2180        suggested_name: Option<String>,
 2181        window: &mut Window,
 2182        cx: &mut Context<Self>,
 2183    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2184        if self.project.read(cx).is_via_collab()
 2185            || self.project.read(cx).is_via_remote_server()
 2186            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2187        {
 2188            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2189            let rx = prompt(self, lister, window, cx);
 2190            self.on_prompt_for_new_path = Some(prompt);
 2191            return rx;
 2192        }
 2193
 2194        let (tx, rx) = oneshot::channel();
 2195        cx.spawn_in(window, async move |workspace, cx| {
 2196            let abs_path = workspace.update(cx, |workspace, cx| {
 2197                let relative_to = workspace
 2198                    .most_recent_active_path(cx)
 2199                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2200                    .or_else(|| {
 2201                        let project = workspace.project.read(cx);
 2202                        project.visible_worktrees(cx).find_map(|worktree| {
 2203                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2204                        })
 2205                    })
 2206                    .or_else(std::env::home_dir)
 2207                    .unwrap_or_else(|| PathBuf::from(""));
 2208                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2209            })?;
 2210            let abs_path = match abs_path.await? {
 2211                Ok(path) => path,
 2212                Err(err) => {
 2213                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2214                        workspace.show_portal_error(err.to_string(), cx);
 2215
 2216                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2217                        let rx = prompt(workspace, lister, window, cx);
 2218                        workspace.on_prompt_for_new_path = Some(prompt);
 2219                        rx
 2220                    })?;
 2221                    if let Ok(path) = rx.await {
 2222                        tx.send(path).ok();
 2223                    }
 2224                    return anyhow::Ok(());
 2225                }
 2226            };
 2227
 2228            tx.send(abs_path.map(|path| vec![path])).ok();
 2229            anyhow::Ok(())
 2230        })
 2231        .detach();
 2232
 2233        rx
 2234    }
 2235
 2236    pub fn titlebar_item(&self) -> Option<AnyView> {
 2237        self.titlebar_item.clone()
 2238    }
 2239
 2240    /// Call the given callback with a workspace whose project is local.
 2241    ///
 2242    /// If the given workspace has a local project, then it will be passed
 2243    /// to the callback. Otherwise, a new empty window will be created.
 2244    pub fn with_local_workspace<T, F>(
 2245        &mut self,
 2246        window: &mut Window,
 2247        cx: &mut Context<Self>,
 2248        callback: F,
 2249    ) -> Task<Result<T>>
 2250    where
 2251        T: 'static,
 2252        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2253    {
 2254        if self.project.read(cx).is_local() {
 2255            Task::ready(Ok(callback(self, window, cx)))
 2256        } else {
 2257            let env = self.project.read(cx).cli_environment(cx);
 2258            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
 2259            cx.spawn_in(window, async move |_vh, cx| {
 2260                let (workspace, _) = task.await?;
 2261                workspace.update(cx, callback)
 2262            })
 2263        }
 2264    }
 2265
 2266    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2267        self.project.read(cx).worktrees(cx)
 2268    }
 2269
 2270    pub fn visible_worktrees<'a>(
 2271        &self,
 2272        cx: &'a App,
 2273    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2274        self.project.read(cx).visible_worktrees(cx)
 2275    }
 2276
 2277    #[cfg(any(test, feature = "test-support"))]
 2278    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2279        let futures = self
 2280            .worktrees(cx)
 2281            .filter_map(|worktree| worktree.read(cx).as_local())
 2282            .map(|worktree| worktree.scan_complete())
 2283            .collect::<Vec<_>>();
 2284        async move {
 2285            for future in futures {
 2286                future.await;
 2287            }
 2288        }
 2289    }
 2290
 2291    pub fn close_global(cx: &mut App) {
 2292        cx.defer(|cx| {
 2293            cx.windows().iter().find(|window| {
 2294                window
 2295                    .update(cx, |_, window, _| {
 2296                        if window.is_window_active() {
 2297                            //This can only get called when the window's project connection has been lost
 2298                            //so we don't need to prompt the user for anything and instead just close the window
 2299                            window.remove_window();
 2300                            true
 2301                        } else {
 2302                            false
 2303                        }
 2304                    })
 2305                    .unwrap_or(false)
 2306            });
 2307        });
 2308    }
 2309
 2310    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2311        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2312        cx.spawn_in(window, async move |_, cx| {
 2313            if prepare.await? {
 2314                cx.update(|window, _cx| window.remove_window())?;
 2315            }
 2316            anyhow::Ok(())
 2317        })
 2318        .detach_and_log_err(cx)
 2319    }
 2320
 2321    pub fn move_focused_panel_to_next_position(
 2322        &mut self,
 2323        _: &MoveFocusedPanelToNextPosition,
 2324        window: &mut Window,
 2325        cx: &mut Context<Self>,
 2326    ) {
 2327        let docks = self.all_docks();
 2328        let active_dock = docks
 2329            .into_iter()
 2330            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2331
 2332        if let Some(dock) = active_dock {
 2333            dock.update(cx, |dock, cx| {
 2334                let active_panel = dock
 2335                    .active_panel()
 2336                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2337
 2338                if let Some(panel) = active_panel {
 2339                    panel.move_to_next_position(window, cx);
 2340                }
 2341            })
 2342        }
 2343    }
 2344
 2345    pub fn prepare_to_close(
 2346        &mut self,
 2347        close_intent: CloseIntent,
 2348        window: &mut Window,
 2349        cx: &mut Context<Self>,
 2350    ) -> Task<Result<bool>> {
 2351        let active_call = self.active_call().cloned();
 2352
 2353        // On Linux and Windows, closing the last window should restore the last workspace.
 2354        let save_last_workspace = cfg!(not(target_os = "macos"))
 2355            && close_intent != CloseIntent::ReplaceWindow
 2356            && cx.windows().len() == 1;
 2357
 2358        cx.spawn_in(window, async move |this, cx| {
 2359            let workspace_count = cx.update(|_window, cx| {
 2360                cx.windows()
 2361                    .iter()
 2362                    .filter(|window| window.downcast::<Workspace>().is_some())
 2363                    .count()
 2364            })?;
 2365
 2366            if let Some(active_call) = active_call
 2367                && workspace_count == 1
 2368                && active_call.read_with(cx, |call, _| call.room().is_some())?
 2369            {
 2370                if close_intent == CloseIntent::CloseWindow {
 2371                    let answer = cx.update(|window, cx| {
 2372                        window.prompt(
 2373                            PromptLevel::Warning,
 2374                            "Do you want to leave the current call?",
 2375                            None,
 2376                            &["Close window and hang up", "Cancel"],
 2377                            cx,
 2378                        )
 2379                    })?;
 2380
 2381                    if answer.await.log_err() == Some(1) {
 2382                        return anyhow::Ok(false);
 2383                    } else {
 2384                        active_call
 2385                            .update(cx, |call, cx| call.hang_up(cx))?
 2386                            .await
 2387                            .log_err();
 2388                    }
 2389                }
 2390                if close_intent == CloseIntent::ReplaceWindow {
 2391                    _ = active_call.update(cx, |this, cx| {
 2392                        let workspace = cx
 2393                            .windows()
 2394                            .iter()
 2395                            .filter_map(|window| window.downcast::<Workspace>())
 2396                            .next()
 2397                            .unwrap();
 2398                        let project = workspace.read(cx)?.project.clone();
 2399                        if project.read(cx).is_shared() {
 2400                            this.unshare_project(project, cx)?;
 2401                        }
 2402                        Ok::<_, anyhow::Error>(())
 2403                    })?;
 2404                }
 2405            }
 2406
 2407            let save_result = this
 2408                .update_in(cx, |this, window, cx| {
 2409                    this.save_all_internal(SaveIntent::Close, window, cx)
 2410                })?
 2411                .await;
 2412
 2413            // If we're not quitting, but closing, we remove the workspace from
 2414            // the current session.
 2415            if close_intent != CloseIntent::Quit
 2416                && !save_last_workspace
 2417                && save_result.as_ref().is_ok_and(|&res| res)
 2418            {
 2419                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2420                    .await;
 2421            }
 2422
 2423            save_result
 2424        })
 2425    }
 2426
 2427    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2428        self.save_all_internal(
 2429            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2430            window,
 2431            cx,
 2432        )
 2433        .detach_and_log_err(cx);
 2434    }
 2435
 2436    fn send_keystrokes(
 2437        &mut self,
 2438        action: &SendKeystrokes,
 2439        window: &mut Window,
 2440        cx: &mut Context<Self>,
 2441    ) {
 2442        let keystrokes: Vec<Keystroke> = action
 2443            .0
 2444            .split(' ')
 2445            .flat_map(|k| Keystroke::parse(k).log_err())
 2446            .collect();
 2447        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2448    }
 2449
 2450    pub fn send_keystrokes_impl(
 2451        &mut self,
 2452        keystrokes: Vec<Keystroke>,
 2453        window: &mut Window,
 2454        cx: &mut Context<Self>,
 2455    ) -> Shared<Task<()>> {
 2456        let mut state = self.dispatching_keystrokes.borrow_mut();
 2457        if !state.dispatched.insert(keystrokes.clone()) {
 2458            cx.propagate();
 2459            return state.task.clone().unwrap();
 2460        }
 2461
 2462        state.queue.extend(keystrokes);
 2463
 2464        let keystrokes = self.dispatching_keystrokes.clone();
 2465        if state.task.is_none() {
 2466            state.task = Some(
 2467                window
 2468                    .spawn(cx, async move |cx| {
 2469                        // limit to 100 keystrokes to avoid infinite recursion.
 2470                        for _ in 0..100 {
 2471                            let mut state = keystrokes.borrow_mut();
 2472                            let Some(keystroke) = state.queue.pop_front() else {
 2473                                state.dispatched.clear();
 2474                                state.task.take();
 2475                                return;
 2476                            };
 2477                            drop(state);
 2478                            cx.update(|window, cx| {
 2479                                let focused = window.focused(cx);
 2480                                window.dispatch_keystroke(keystroke.clone(), cx);
 2481                                if window.focused(cx) != focused {
 2482                                    // dispatch_keystroke may cause the focus to change.
 2483                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2484                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2485                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2486                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2487                                    // )
 2488                                    window.draw(cx).clear();
 2489                                }
 2490                            })
 2491                            .ok();
 2492                        }
 2493
 2494                        *keystrokes.borrow_mut() = Default::default();
 2495                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2496                    })
 2497                    .shared(),
 2498            );
 2499        }
 2500        state.task.clone().unwrap()
 2501    }
 2502
 2503    fn save_all_internal(
 2504        &mut self,
 2505        mut save_intent: SaveIntent,
 2506        window: &mut Window,
 2507        cx: &mut Context<Self>,
 2508    ) -> Task<Result<bool>> {
 2509        if self.project.read(cx).is_disconnected(cx) {
 2510            return Task::ready(Ok(true));
 2511        }
 2512        let dirty_items = self
 2513            .panes
 2514            .iter()
 2515            .flat_map(|pane| {
 2516                pane.read(cx).items().filter_map(|item| {
 2517                    if item.is_dirty(cx) {
 2518                        item.tab_content_text(0, cx);
 2519                        Some((pane.downgrade(), item.boxed_clone()))
 2520                    } else {
 2521                        None
 2522                    }
 2523                })
 2524            })
 2525            .collect::<Vec<_>>();
 2526
 2527        let project = self.project.clone();
 2528        cx.spawn_in(window, async move |workspace, cx| {
 2529            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2530                let (serialize_tasks, remaining_dirty_items) =
 2531                    workspace.update_in(cx, |workspace, window, cx| {
 2532                        let mut remaining_dirty_items = Vec::new();
 2533                        let mut serialize_tasks = Vec::new();
 2534                        for (pane, item) in dirty_items {
 2535                            if let Some(task) = item
 2536                                .to_serializable_item_handle(cx)
 2537                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2538                            {
 2539                                serialize_tasks.push(task);
 2540                            } else {
 2541                                remaining_dirty_items.push((pane, item));
 2542                            }
 2543                        }
 2544                        (serialize_tasks, remaining_dirty_items)
 2545                    })?;
 2546
 2547                futures::future::try_join_all(serialize_tasks).await?;
 2548
 2549                if remaining_dirty_items.len() > 1 {
 2550                    let answer = workspace.update_in(cx, |_, window, cx| {
 2551                        let detail = Pane::file_names_for_prompt(
 2552                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2553                            cx,
 2554                        );
 2555                        window.prompt(
 2556                            PromptLevel::Warning,
 2557                            "Do you want to save all changes in the following files?",
 2558                            Some(&detail),
 2559                            &["Save all", "Discard all", "Cancel"],
 2560                            cx,
 2561                        )
 2562                    })?;
 2563                    match answer.await.log_err() {
 2564                        Some(0) => save_intent = SaveIntent::SaveAll,
 2565                        Some(1) => save_intent = SaveIntent::Skip,
 2566                        Some(2) => return Ok(false),
 2567                        _ => {}
 2568                    }
 2569                }
 2570
 2571                remaining_dirty_items
 2572            } else {
 2573                dirty_items
 2574            };
 2575
 2576            for (pane, item) in dirty_items {
 2577                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2578                    (
 2579                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2580                        item.project_entry_ids(cx),
 2581                    )
 2582                })?;
 2583                if (singleton || !project_entry_ids.is_empty())
 2584                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2585                {
 2586                    return Ok(false);
 2587                }
 2588            }
 2589            Ok(true)
 2590        })
 2591    }
 2592
 2593    pub fn open_workspace_for_paths(
 2594        &mut self,
 2595        replace_current_window: bool,
 2596        paths: Vec<PathBuf>,
 2597        window: &mut Window,
 2598        cx: &mut Context<Self>,
 2599    ) -> Task<Result<()>> {
 2600        let window_handle = window.window_handle().downcast::<Self>();
 2601        let is_remote = self.project.read(cx).is_via_collab();
 2602        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2603        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2604
 2605        let window_to_replace = if replace_current_window {
 2606            window_handle
 2607        } else if is_remote || has_worktree || has_dirty_items {
 2608            None
 2609        } else {
 2610            window_handle
 2611        };
 2612        let app_state = self.app_state.clone();
 2613
 2614        cx.spawn(async move |_, cx| {
 2615            cx.update(|cx| {
 2616                open_paths(
 2617                    &paths,
 2618                    app_state,
 2619                    OpenOptions {
 2620                        replace_window: window_to_replace,
 2621                        ..Default::default()
 2622                    },
 2623                    cx,
 2624                )
 2625            })?
 2626            .await?;
 2627            Ok(())
 2628        })
 2629    }
 2630
 2631    #[allow(clippy::type_complexity)]
 2632    pub fn open_paths(
 2633        &mut self,
 2634        mut abs_paths: Vec<PathBuf>,
 2635        options: OpenOptions,
 2636        pane: Option<WeakEntity<Pane>>,
 2637        window: &mut Window,
 2638        cx: &mut Context<Self>,
 2639    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2640        let fs = self.app_state.fs.clone();
 2641
 2642        // Sort the paths to ensure we add worktrees for parents before their children.
 2643        abs_paths.sort_unstable();
 2644        cx.spawn_in(window, async move |this, cx| {
 2645            let mut tasks = Vec::with_capacity(abs_paths.len());
 2646
 2647            for abs_path in &abs_paths {
 2648                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2649                    OpenVisible::All => Some(true),
 2650                    OpenVisible::None => Some(false),
 2651                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2652                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2653                        Some(None) => Some(true),
 2654                        None => None,
 2655                    },
 2656                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2657                        Some(Some(metadata)) => Some(metadata.is_dir),
 2658                        Some(None) => Some(false),
 2659                        None => None,
 2660                    },
 2661                };
 2662                let project_path = match visible {
 2663                    Some(visible) => match this
 2664                        .update(cx, |this, cx| {
 2665                            Workspace::project_path_for_path(
 2666                                this.project.clone(),
 2667                                abs_path,
 2668                                visible,
 2669                                cx,
 2670                            )
 2671                        })
 2672                        .log_err()
 2673                    {
 2674                        Some(project_path) => project_path.await.log_err(),
 2675                        None => None,
 2676                    },
 2677                    None => None,
 2678                };
 2679
 2680                let this = this.clone();
 2681                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 2682                let fs = fs.clone();
 2683                let pane = pane.clone();
 2684                let task = cx.spawn(async move |cx| {
 2685                    let (worktree, project_path) = project_path?;
 2686                    if fs.is_dir(&abs_path).await {
 2687                        this.update(cx, |workspace, cx| {
 2688                            let worktree = worktree.read(cx);
 2689                            let worktree_abs_path = worktree.abs_path();
 2690                            let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
 2691                                worktree.root_entry()
 2692                            } else {
 2693                                abs_path
 2694                                    .strip_prefix(worktree_abs_path.as_ref())
 2695                                    .ok()
 2696                                    .and_then(|relative_path| {
 2697                                        let relative_path =
 2698                                            RelPath::new(relative_path, PathStyle::local())
 2699                                                .log_err()?;
 2700                                        worktree.entry_for_path(&relative_path)
 2701                                    })
 2702                            }
 2703                            .map(|entry| entry.id);
 2704                            if let Some(entry_id) = entry_id {
 2705                                workspace.project.update(cx, |_, cx| {
 2706                                    cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 2707                                })
 2708                            }
 2709                        })
 2710                        .ok()?;
 2711                        None
 2712                    } else {
 2713                        Some(
 2714                            this.update_in(cx, |this, window, cx| {
 2715                                this.open_path(
 2716                                    project_path,
 2717                                    pane,
 2718                                    options.focus.unwrap_or(true),
 2719                                    window,
 2720                                    cx,
 2721                                )
 2722                            })
 2723                            .ok()?
 2724                            .await,
 2725                        )
 2726                    }
 2727                });
 2728                tasks.push(task);
 2729            }
 2730
 2731            futures::future::join_all(tasks).await
 2732        })
 2733    }
 2734
 2735    pub fn open_resolved_path(
 2736        &mut self,
 2737        path: ResolvedPath,
 2738        window: &mut Window,
 2739        cx: &mut Context<Self>,
 2740    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 2741        match path {
 2742            ResolvedPath::ProjectPath { project_path, .. } => {
 2743                self.open_path(project_path, None, true, window, cx)
 2744            }
 2745            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 2746                PathBuf::from(path),
 2747                OpenOptions {
 2748                    visible: Some(OpenVisible::None),
 2749                    ..Default::default()
 2750                },
 2751                window,
 2752                cx,
 2753            ),
 2754        }
 2755    }
 2756
 2757    pub fn absolute_path_of_worktree(
 2758        &self,
 2759        worktree_id: WorktreeId,
 2760        cx: &mut Context<Self>,
 2761    ) -> Option<PathBuf> {
 2762        self.project
 2763            .read(cx)
 2764            .worktree_for_id(worktree_id, cx)
 2765            // TODO: use `abs_path` or `root_dir`
 2766            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 2767    }
 2768
 2769    fn add_folder_to_project(
 2770        &mut self,
 2771        _: &AddFolderToProject,
 2772        window: &mut Window,
 2773        cx: &mut Context<Self>,
 2774    ) {
 2775        let project = self.project.read(cx);
 2776        if project.is_via_collab() {
 2777            self.show_error(
 2778                &anyhow!("You cannot add folders to someone else's project"),
 2779                cx,
 2780            );
 2781            return;
 2782        }
 2783        let paths = self.prompt_for_open_path(
 2784            PathPromptOptions {
 2785                files: false,
 2786                directories: true,
 2787                multiple: true,
 2788                prompt: None,
 2789            },
 2790            DirectoryLister::Project(self.project.clone()),
 2791            window,
 2792            cx,
 2793        );
 2794        cx.spawn_in(window, async move |this, cx| {
 2795            if let Some(paths) = paths.await.log_err().flatten() {
 2796                let results = this
 2797                    .update_in(cx, |this, window, cx| {
 2798                        this.open_paths(
 2799                            paths,
 2800                            OpenOptions {
 2801                                visible: Some(OpenVisible::All),
 2802                                ..Default::default()
 2803                            },
 2804                            None,
 2805                            window,
 2806                            cx,
 2807                        )
 2808                    })?
 2809                    .await;
 2810                for result in results.into_iter().flatten() {
 2811                    result.log_err();
 2812                }
 2813            }
 2814            anyhow::Ok(())
 2815        })
 2816        .detach_and_log_err(cx);
 2817    }
 2818
 2819    pub fn project_path_for_path(
 2820        project: Entity<Project>,
 2821        abs_path: &Path,
 2822        visible: bool,
 2823        cx: &mut App,
 2824    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 2825        let entry = project.update(cx, |project, cx| {
 2826            project.find_or_create_worktree(abs_path, visible, cx)
 2827        });
 2828        cx.spawn(async move |cx| {
 2829            let (worktree, path) = entry.await?;
 2830            let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
 2831            Ok((
 2832                worktree,
 2833                ProjectPath {
 2834                    worktree_id,
 2835                    path: path,
 2836                },
 2837            ))
 2838        })
 2839    }
 2840
 2841    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 2842        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 2843    }
 2844
 2845    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 2846        self.items_of_type(cx).max_by_key(|item| item.item_id())
 2847    }
 2848
 2849    pub fn items_of_type<'a, T: Item>(
 2850        &'a self,
 2851        cx: &'a App,
 2852    ) -> impl 'a + Iterator<Item = Entity<T>> {
 2853        self.panes
 2854            .iter()
 2855            .flat_map(|pane| pane.read(cx).items_of_type())
 2856    }
 2857
 2858    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 2859        self.active_pane().read(cx).active_item()
 2860    }
 2861
 2862    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 2863        let item = self.active_item(cx)?;
 2864        item.to_any().downcast::<I>().ok()
 2865    }
 2866
 2867    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 2868        self.active_item(cx).and_then(|item| item.project_path(cx))
 2869    }
 2870
 2871    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 2872        self.recent_navigation_history_iter(cx)
 2873            .filter_map(|(path, abs_path)| {
 2874                let worktree = self
 2875                    .project
 2876                    .read(cx)
 2877                    .worktree_for_id(path.worktree_id, cx)?;
 2878                if worktree.read(cx).is_visible() {
 2879                    abs_path
 2880                } else {
 2881                    None
 2882                }
 2883            })
 2884            .next()
 2885    }
 2886
 2887    pub fn save_active_item(
 2888        &mut self,
 2889        save_intent: SaveIntent,
 2890        window: &mut Window,
 2891        cx: &mut App,
 2892    ) -> Task<Result<()>> {
 2893        let project = self.project.clone();
 2894        let pane = self.active_pane();
 2895        let item = pane.read(cx).active_item();
 2896        let pane = pane.downgrade();
 2897
 2898        window.spawn(cx, async move |cx| {
 2899            if let Some(item) = item {
 2900                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 2901                    .await
 2902                    .map(|_| ())
 2903            } else {
 2904                Ok(())
 2905            }
 2906        })
 2907    }
 2908
 2909    pub fn close_inactive_items_and_panes(
 2910        &mut self,
 2911        action: &CloseInactiveTabsAndPanes,
 2912        window: &mut Window,
 2913        cx: &mut Context<Self>,
 2914    ) {
 2915        if let Some(task) = self.close_all_internal(
 2916            true,
 2917            action.save_intent.unwrap_or(SaveIntent::Close),
 2918            window,
 2919            cx,
 2920        ) {
 2921            task.detach_and_log_err(cx)
 2922        }
 2923    }
 2924
 2925    pub fn close_all_items_and_panes(
 2926        &mut self,
 2927        action: &CloseAllItemsAndPanes,
 2928        window: &mut Window,
 2929        cx: &mut Context<Self>,
 2930    ) {
 2931        if let Some(task) = self.close_all_internal(
 2932            false,
 2933            action.save_intent.unwrap_or(SaveIntent::Close),
 2934            window,
 2935            cx,
 2936        ) {
 2937            task.detach_and_log_err(cx)
 2938        }
 2939    }
 2940
 2941    fn close_all_internal(
 2942        &mut self,
 2943        retain_active_pane: bool,
 2944        save_intent: SaveIntent,
 2945        window: &mut Window,
 2946        cx: &mut Context<Self>,
 2947    ) -> Option<Task<Result<()>>> {
 2948        let current_pane = self.active_pane();
 2949
 2950        let mut tasks = Vec::new();
 2951
 2952        if retain_active_pane {
 2953            let current_pane_close = current_pane.update(cx, |pane, cx| {
 2954                pane.close_other_items(
 2955                    &CloseOtherItems {
 2956                        save_intent: None,
 2957                        close_pinned: false,
 2958                    },
 2959                    None,
 2960                    window,
 2961                    cx,
 2962                )
 2963            });
 2964
 2965            tasks.push(current_pane_close);
 2966        }
 2967
 2968        for pane in self.panes() {
 2969            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 2970                continue;
 2971            }
 2972
 2973            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 2974                pane.close_all_items(
 2975                    &CloseAllItems {
 2976                        save_intent: Some(save_intent),
 2977                        close_pinned: false,
 2978                    },
 2979                    window,
 2980                    cx,
 2981                )
 2982            });
 2983
 2984            tasks.push(close_pane_items)
 2985        }
 2986
 2987        if tasks.is_empty() {
 2988            None
 2989        } else {
 2990            Some(cx.spawn_in(window, async move |_, _| {
 2991                for task in tasks {
 2992                    task.await?
 2993                }
 2994                Ok(())
 2995            }))
 2996        }
 2997    }
 2998
 2999    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3000        self.dock_at_position(position).read(cx).is_open()
 3001    }
 3002
 3003    pub fn toggle_dock(
 3004        &mut self,
 3005        dock_side: DockPosition,
 3006        window: &mut Window,
 3007        cx: &mut Context<Self>,
 3008    ) {
 3009        let mut focus_center = false;
 3010        let mut reveal_dock = false;
 3011
 3012        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3013        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3014        if was_visible {
 3015            self.save_open_dock_positions(cx);
 3016        }
 3017
 3018        let dock = self.dock_at_position(dock_side);
 3019        dock.update(cx, |dock, cx| {
 3020            dock.set_open(!was_visible, window, cx);
 3021
 3022            if dock.active_panel().is_none() {
 3023                let Some(panel_ix) = dock
 3024                    .first_enabled_panel_idx(cx)
 3025                    .log_with_level(log::Level::Info)
 3026                else {
 3027                    return;
 3028                };
 3029                dock.activate_panel(panel_ix, window, cx);
 3030            }
 3031
 3032            if let Some(active_panel) = dock.active_panel() {
 3033                if was_visible {
 3034                    if active_panel
 3035                        .panel_focus_handle(cx)
 3036                        .contains_focused(window, cx)
 3037                    {
 3038                        focus_center = true;
 3039                    }
 3040                } else {
 3041                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3042                    window.focus(focus_handle);
 3043                    reveal_dock = true;
 3044                }
 3045            }
 3046        });
 3047
 3048        if reveal_dock {
 3049            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3050        }
 3051
 3052        if focus_center {
 3053            self.active_pane
 3054                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3055        }
 3056
 3057        cx.notify();
 3058        self.serialize_workspace(window, cx);
 3059    }
 3060
 3061    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3062        self.all_docks().into_iter().find(|&dock| {
 3063            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3064        })
 3065    }
 3066
 3067    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3068        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3069            self.save_open_dock_positions(cx);
 3070            dock.update(cx, |dock, cx| {
 3071                dock.set_open(false, window, cx);
 3072            });
 3073            return true;
 3074        }
 3075        false
 3076    }
 3077
 3078    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3079        self.save_open_dock_positions(cx);
 3080        for dock in self.all_docks() {
 3081            dock.update(cx, |dock, cx| {
 3082                dock.set_open(false, window, cx);
 3083            });
 3084        }
 3085
 3086        cx.focus_self(window);
 3087        cx.notify();
 3088        self.serialize_workspace(window, cx);
 3089    }
 3090
 3091    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3092        self.all_docks()
 3093            .into_iter()
 3094            .filter_map(|dock| {
 3095                let dock_ref = dock.read(cx);
 3096                if dock_ref.is_open() {
 3097                    Some(dock_ref.position())
 3098                } else {
 3099                    None
 3100                }
 3101            })
 3102            .collect()
 3103    }
 3104
 3105    /// Saves the positions of currently open docks.
 3106    ///
 3107    /// Updates `last_open_dock_positions` with positions of all currently open
 3108    /// docks, to later be restored by the 'Toggle All Docks' action.
 3109    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3110        let open_dock_positions = self.get_open_dock_positions(cx);
 3111        if !open_dock_positions.is_empty() {
 3112            self.last_open_dock_positions = open_dock_positions;
 3113        }
 3114    }
 3115
 3116    /// Toggles all docks between open and closed states.
 3117    ///
 3118    /// If any docks are open, closes all and remembers their positions. If all
 3119    /// docks are closed, restores the last remembered dock configuration.
 3120    fn toggle_all_docks(
 3121        &mut self,
 3122        _: &ToggleAllDocks,
 3123        window: &mut Window,
 3124        cx: &mut Context<Self>,
 3125    ) {
 3126        let open_dock_positions = self.get_open_dock_positions(cx);
 3127
 3128        if !open_dock_positions.is_empty() {
 3129            self.close_all_docks(window, cx);
 3130        } else if !self.last_open_dock_positions.is_empty() {
 3131            self.restore_last_open_docks(window, cx);
 3132        }
 3133    }
 3134
 3135    /// Reopens docks from the most recently remembered configuration.
 3136    ///
 3137    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3138    /// and clears the stored positions.
 3139    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3140        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3141
 3142        for position in positions_to_open {
 3143            let dock = self.dock_at_position(position);
 3144            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3145        }
 3146
 3147        cx.focus_self(window);
 3148        cx.notify();
 3149        self.serialize_workspace(window, cx);
 3150    }
 3151
 3152    /// Transfer focus to the panel of the given type.
 3153    pub fn focus_panel<T: Panel>(
 3154        &mut self,
 3155        window: &mut Window,
 3156        cx: &mut Context<Self>,
 3157    ) -> Option<Entity<T>> {
 3158        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 3159        panel.to_any().downcast().ok()
 3160    }
 3161
 3162    /// Focus the panel of the given type if it isn't already focused. If it is
 3163    /// already focused, then transfer focus back to the workspace center.
 3164    pub fn toggle_panel_focus<T: Panel>(
 3165        &mut self,
 3166        window: &mut Window,
 3167        cx: &mut Context<Self>,
 3168    ) -> bool {
 3169        let mut did_focus_panel = false;
 3170        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3171            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3172            did_focus_panel
 3173        });
 3174        did_focus_panel
 3175    }
 3176
 3177    pub fn activate_panel_for_proto_id(
 3178        &mut self,
 3179        panel_id: PanelId,
 3180        window: &mut Window,
 3181        cx: &mut Context<Self>,
 3182    ) -> Option<Arc<dyn PanelHandle>> {
 3183        let mut panel = None;
 3184        for dock in self.all_docks() {
 3185            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3186                panel = dock.update(cx, |dock, cx| {
 3187                    dock.activate_panel(panel_index, window, cx);
 3188                    dock.set_open(true, window, cx);
 3189                    dock.active_panel().cloned()
 3190                });
 3191                break;
 3192            }
 3193        }
 3194
 3195        if panel.is_some() {
 3196            cx.notify();
 3197            self.serialize_workspace(window, cx);
 3198        }
 3199
 3200        panel
 3201    }
 3202
 3203    /// Focus or unfocus the given panel type, depending on the given callback.
 3204    fn focus_or_unfocus_panel<T: Panel>(
 3205        &mut self,
 3206        window: &mut Window,
 3207        cx: &mut Context<Self>,
 3208        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3209    ) -> Option<Arc<dyn PanelHandle>> {
 3210        let mut result_panel = None;
 3211        let mut serialize = false;
 3212        for dock in self.all_docks() {
 3213            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3214                let mut focus_center = false;
 3215                let panel = dock.update(cx, |dock, cx| {
 3216                    dock.activate_panel(panel_index, window, cx);
 3217
 3218                    let panel = dock.active_panel().cloned();
 3219                    if let Some(panel) = panel.as_ref() {
 3220                        if should_focus(&**panel, window, cx) {
 3221                            dock.set_open(true, window, cx);
 3222                            panel.panel_focus_handle(cx).focus(window);
 3223                        } else {
 3224                            focus_center = true;
 3225                        }
 3226                    }
 3227                    panel
 3228                });
 3229
 3230                if focus_center {
 3231                    self.active_pane
 3232                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3233                }
 3234
 3235                result_panel = panel;
 3236                serialize = true;
 3237                break;
 3238            }
 3239        }
 3240
 3241        if serialize {
 3242            self.serialize_workspace(window, cx);
 3243        }
 3244
 3245        cx.notify();
 3246        result_panel
 3247    }
 3248
 3249    /// Open the panel of the given type
 3250    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3251        for dock in self.all_docks() {
 3252            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3253                dock.update(cx, |dock, cx| {
 3254                    dock.activate_panel(panel_index, window, cx);
 3255                    dock.set_open(true, window, cx);
 3256                });
 3257            }
 3258        }
 3259    }
 3260
 3261    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3262        for dock in self.all_docks().iter() {
 3263            dock.update(cx, |dock, cx| {
 3264                if dock.panel::<T>().is_some() {
 3265                    dock.set_open(false, window, cx)
 3266                }
 3267            })
 3268        }
 3269    }
 3270
 3271    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3272        self.all_docks()
 3273            .iter()
 3274            .find_map(|dock| dock.read(cx).panel::<T>())
 3275    }
 3276
 3277    fn dismiss_zoomed_items_to_reveal(
 3278        &mut self,
 3279        dock_to_reveal: Option<DockPosition>,
 3280        window: &mut Window,
 3281        cx: &mut Context<Self>,
 3282    ) {
 3283        // If a center pane is zoomed, unzoom it.
 3284        for pane in &self.panes {
 3285            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3286                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3287            }
 3288        }
 3289
 3290        // If another dock is zoomed, hide it.
 3291        let mut focus_center = false;
 3292        for dock in self.all_docks() {
 3293            dock.update(cx, |dock, cx| {
 3294                if Some(dock.position()) != dock_to_reveal
 3295                    && let Some(panel) = dock.active_panel()
 3296                    && panel.is_zoomed(window, cx)
 3297                {
 3298                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3299                    dock.set_open(false, window, cx);
 3300                }
 3301            });
 3302        }
 3303
 3304        if focus_center {
 3305            self.active_pane
 3306                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3307        }
 3308
 3309        if self.zoomed_position != dock_to_reveal {
 3310            self.zoomed = None;
 3311            self.zoomed_position = None;
 3312            cx.emit(Event::ZoomChanged);
 3313        }
 3314
 3315        cx.notify();
 3316    }
 3317
 3318    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3319        let pane = cx.new(|cx| {
 3320            let mut pane = Pane::new(
 3321                self.weak_handle(),
 3322                self.project.clone(),
 3323                self.pane_history_timestamp.clone(),
 3324                None,
 3325                NewFile.boxed_clone(),
 3326                true,
 3327                window,
 3328                cx,
 3329            );
 3330            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3331            pane
 3332        });
 3333        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3334            .detach();
 3335        self.panes.push(pane.clone());
 3336
 3337        window.focus(&pane.focus_handle(cx));
 3338
 3339        cx.emit(Event::PaneAdded(pane.clone()));
 3340        pane
 3341    }
 3342
 3343    pub fn add_item_to_center(
 3344        &mut self,
 3345        item: Box<dyn ItemHandle>,
 3346        window: &mut Window,
 3347        cx: &mut Context<Self>,
 3348    ) -> bool {
 3349        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3350            if let Some(center_pane) = center_pane.upgrade() {
 3351                center_pane.update(cx, |pane, cx| {
 3352                    pane.add_item(item, true, true, None, window, cx)
 3353                });
 3354                true
 3355            } else {
 3356                false
 3357            }
 3358        } else {
 3359            false
 3360        }
 3361    }
 3362
 3363    pub fn add_item_to_active_pane(
 3364        &mut self,
 3365        item: Box<dyn ItemHandle>,
 3366        destination_index: Option<usize>,
 3367        focus_item: bool,
 3368        window: &mut Window,
 3369        cx: &mut App,
 3370    ) {
 3371        self.add_item(
 3372            self.active_pane.clone(),
 3373            item,
 3374            destination_index,
 3375            false,
 3376            focus_item,
 3377            window,
 3378            cx,
 3379        )
 3380    }
 3381
 3382    pub fn add_item(
 3383        &mut self,
 3384        pane: Entity<Pane>,
 3385        item: Box<dyn ItemHandle>,
 3386        destination_index: Option<usize>,
 3387        activate_pane: bool,
 3388        focus_item: bool,
 3389        window: &mut Window,
 3390        cx: &mut App,
 3391    ) {
 3392        pane.update(cx, |pane, cx| {
 3393            pane.add_item(
 3394                item,
 3395                activate_pane,
 3396                focus_item,
 3397                destination_index,
 3398                window,
 3399                cx,
 3400            )
 3401        });
 3402    }
 3403
 3404    pub fn split_item(
 3405        &mut self,
 3406        split_direction: SplitDirection,
 3407        item: Box<dyn ItemHandle>,
 3408        window: &mut Window,
 3409        cx: &mut Context<Self>,
 3410    ) {
 3411        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3412        self.add_item(new_pane, item, None, true, true, window, cx);
 3413    }
 3414
 3415    pub fn open_abs_path(
 3416        &mut self,
 3417        abs_path: PathBuf,
 3418        options: OpenOptions,
 3419        window: &mut Window,
 3420        cx: &mut Context<Self>,
 3421    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3422        cx.spawn_in(window, async move |workspace, cx| {
 3423            let open_paths_task_result = workspace
 3424                .update_in(cx, |workspace, window, cx| {
 3425                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3426                })
 3427                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3428                .await;
 3429            anyhow::ensure!(
 3430                open_paths_task_result.len() == 1,
 3431                "open abs path {abs_path:?} task returned incorrect number of results"
 3432            );
 3433            match open_paths_task_result
 3434                .into_iter()
 3435                .next()
 3436                .expect("ensured single task result")
 3437            {
 3438                Some(open_result) => {
 3439                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3440                }
 3441                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3442            }
 3443        })
 3444    }
 3445
 3446    pub fn split_abs_path(
 3447        &mut self,
 3448        abs_path: PathBuf,
 3449        visible: bool,
 3450        window: &mut Window,
 3451        cx: &mut Context<Self>,
 3452    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3453        let project_path_task =
 3454            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3455        cx.spawn_in(window, async move |this, cx| {
 3456            let (_, path) = project_path_task.await?;
 3457            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3458                .await
 3459        })
 3460    }
 3461
 3462    pub fn open_path(
 3463        &mut self,
 3464        path: impl Into<ProjectPath>,
 3465        pane: Option<WeakEntity<Pane>>,
 3466        focus_item: bool,
 3467        window: &mut Window,
 3468        cx: &mut App,
 3469    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3470        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3471    }
 3472
 3473    pub fn open_path_preview(
 3474        &mut self,
 3475        path: impl Into<ProjectPath>,
 3476        pane: Option<WeakEntity<Pane>>,
 3477        focus_item: bool,
 3478        allow_preview: bool,
 3479        activate: bool,
 3480        window: &mut Window,
 3481        cx: &mut App,
 3482    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3483        let pane = pane.unwrap_or_else(|| {
 3484            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3485                self.panes
 3486                    .first()
 3487                    .expect("There must be an active pane")
 3488                    .downgrade()
 3489            })
 3490        });
 3491
 3492        let project_path = path.into();
 3493        let task = self.load_path(project_path.clone(), window, cx);
 3494        window.spawn(cx, async move |cx| {
 3495            let (project_entry_id, build_item) = task.await?;
 3496
 3497            pane.update_in(cx, |pane, window, cx| {
 3498                pane.open_item(
 3499                    project_entry_id,
 3500                    project_path,
 3501                    focus_item,
 3502                    allow_preview,
 3503                    activate,
 3504                    None,
 3505                    window,
 3506                    cx,
 3507                    build_item,
 3508                )
 3509            })
 3510        })
 3511    }
 3512
 3513    pub fn split_path(
 3514        &mut self,
 3515        path: impl Into<ProjectPath>,
 3516        window: &mut Window,
 3517        cx: &mut Context<Self>,
 3518    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3519        self.split_path_preview(path, false, None, window, cx)
 3520    }
 3521
 3522    pub fn split_path_preview(
 3523        &mut self,
 3524        path: impl Into<ProjectPath>,
 3525        allow_preview: bool,
 3526        split_direction: Option<SplitDirection>,
 3527        window: &mut Window,
 3528        cx: &mut Context<Self>,
 3529    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3530        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3531            self.panes
 3532                .first()
 3533                .expect("There must be an active pane")
 3534                .downgrade()
 3535        });
 3536
 3537        if let Member::Pane(center_pane) = &self.center.root
 3538            && center_pane.read(cx).items_len() == 0
 3539        {
 3540            return self.open_path(path, Some(pane), true, window, cx);
 3541        }
 3542
 3543        let project_path = path.into();
 3544        let task = self.load_path(project_path.clone(), window, cx);
 3545        cx.spawn_in(window, async move |this, cx| {
 3546            let (project_entry_id, build_item) = task.await?;
 3547            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3548                let pane = pane.upgrade()?;
 3549                let new_pane = this.split_pane(
 3550                    pane,
 3551                    split_direction.unwrap_or(SplitDirection::Right),
 3552                    window,
 3553                    cx,
 3554                );
 3555                new_pane.update(cx, |new_pane, cx| {
 3556                    Some(new_pane.open_item(
 3557                        project_entry_id,
 3558                        project_path,
 3559                        true,
 3560                        allow_preview,
 3561                        true,
 3562                        None,
 3563                        window,
 3564                        cx,
 3565                        build_item,
 3566                    ))
 3567                })
 3568            })
 3569            .map(|option| option.context("pane was dropped"))?
 3570        })
 3571    }
 3572
 3573    fn load_path(
 3574        &mut self,
 3575        path: ProjectPath,
 3576        window: &mut Window,
 3577        cx: &mut App,
 3578    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3579        let project = self.project();
 3580
 3581        project.update(cx, |project, _| {
 3582            project.encoding_options.force.store(
 3583                self.encoding_options
 3584                    .force
 3585                    .load(std::sync::atomic::Ordering::Relaxed),
 3586                std::sync::atomic::Ordering::Relaxed,
 3587            );
 3588        });
 3589
 3590        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3591        registry.open_path(
 3592            project,
 3593            &path,
 3594            Some(self.encoding_options.encoding.lock().unwrap().clone()),
 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            fs.save(
 7622                path,
 7623                &default_content(),
 7624                Default::default(),
 7625                Default::default(),
 7626            )
 7627            .await?;
 7628        }
 7629
 7630        let mut items = workspace
 7631            .update_in(cx, |workspace, window, cx| {
 7632                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7633                    workspace.open_paths(
 7634                        vec![path.to_path_buf()],
 7635                        OpenOptions {
 7636                            visible: Some(OpenVisible::None),
 7637                            ..Default::default()
 7638                        },
 7639                        None,
 7640                        window,
 7641                        cx,
 7642                    )
 7643                })
 7644            })?
 7645            .await?
 7646            .await;
 7647
 7648        let item = items.pop().flatten();
 7649        item.with_context(|| format!("path {path:?} is not a file"))?
 7650    })
 7651}
 7652
 7653pub fn open_remote_project_with_new_connection(
 7654    window: WindowHandle<Workspace>,
 7655    remote_connection: Arc<dyn RemoteConnection>,
 7656    cancel_rx: oneshot::Receiver<()>,
 7657    delegate: Arc<dyn RemoteClientDelegate>,
 7658    app_state: Arc<AppState>,
 7659    paths: Vec<PathBuf>,
 7660    cx: &mut App,
 7661) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7662    cx.spawn(async move |cx| {
 7663        let (workspace_id, serialized_workspace) =
 7664            serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 7665                .await?;
 7666
 7667        let session = match cx
 7668            .update(|cx| {
 7669                remote::RemoteClient::new(
 7670                    ConnectionIdentifier::Workspace(workspace_id.0),
 7671                    remote_connection,
 7672                    cancel_rx,
 7673                    delegate,
 7674                    cx,
 7675                )
 7676            })?
 7677            .await?
 7678        {
 7679            Some(result) => result,
 7680            None => return Ok(Vec::new()),
 7681        };
 7682
 7683        let project = cx.update(|cx| {
 7684            project::Project::remote(
 7685                session,
 7686                app_state.client.clone(),
 7687                app_state.node_runtime.clone(),
 7688                app_state.user_store.clone(),
 7689                app_state.languages.clone(),
 7690                app_state.fs.clone(),
 7691                cx,
 7692            )
 7693        })?;
 7694
 7695        open_remote_project_inner(
 7696            project,
 7697            paths,
 7698            workspace_id,
 7699            serialized_workspace,
 7700            app_state,
 7701            window,
 7702            cx,
 7703        )
 7704        .await
 7705    })
 7706}
 7707
 7708pub fn open_remote_project_with_existing_connection(
 7709    connection_options: RemoteConnectionOptions,
 7710    project: Entity<Project>,
 7711    paths: Vec<PathBuf>,
 7712    app_state: Arc<AppState>,
 7713    window: WindowHandle<Workspace>,
 7714    cx: &mut AsyncApp,
 7715) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7716    cx.spawn(async move |cx| {
 7717        let (workspace_id, serialized_workspace) =
 7718            serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7719
 7720        open_remote_project_inner(
 7721            project,
 7722            paths,
 7723            workspace_id,
 7724            serialized_workspace,
 7725            app_state,
 7726            window,
 7727            cx,
 7728        )
 7729        .await
 7730    })
 7731}
 7732
 7733async fn open_remote_project_inner(
 7734    project: Entity<Project>,
 7735    paths: Vec<PathBuf>,
 7736    workspace_id: WorkspaceId,
 7737    serialized_workspace: Option<SerializedWorkspace>,
 7738    app_state: Arc<AppState>,
 7739    window: WindowHandle<Workspace>,
 7740    cx: &mut AsyncApp,
 7741) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 7742    let toolchains = DB.toolchains(workspace_id).await?;
 7743    for (toolchain, worktree_id, path) in toolchains {
 7744        project
 7745            .update(cx, |this, cx| {
 7746                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7747            })?
 7748            .await;
 7749    }
 7750    let mut project_paths_to_open = vec![];
 7751    let mut project_path_errors = vec![];
 7752
 7753    for path in paths {
 7754        let result = cx
 7755            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7756            .await;
 7757        match result {
 7758            Ok((_, project_path)) => {
 7759                project_paths_to_open.push((path.clone(), Some(project_path)));
 7760            }
 7761            Err(error) => {
 7762                project_path_errors.push(error);
 7763            }
 7764        };
 7765    }
 7766
 7767    if project_paths_to_open.is_empty() {
 7768        return Err(project_path_errors.pop().context("no paths given")?);
 7769    }
 7770
 7771    if let Some(detach_session_task) = window
 7772        .update(cx, |_workspace, window, cx| {
 7773            cx.spawn_in(window, async move |this, cx| {
 7774                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 7775            })
 7776        })
 7777        .ok()
 7778    {
 7779        detach_session_task.await.ok();
 7780    }
 7781
 7782    cx.update_window(window.into(), |_, window, cx| {
 7783        window.replace_root(cx, |window, cx| {
 7784            telemetry::event!("SSH Project Opened");
 7785
 7786            let mut workspace =
 7787                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7788            workspace.update_history(cx);
 7789
 7790            if let Some(ref serialized) = serialized_workspace {
 7791                workspace.centered_layout = serialized.centered_layout;
 7792            }
 7793
 7794            workspace
 7795        });
 7796    })?;
 7797
 7798    let items = window
 7799        .update(cx, |_, window, cx| {
 7800            window.activate_window();
 7801            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7802        })?
 7803        .await?;
 7804
 7805    window.update(cx, |workspace, _, cx| {
 7806        for error in project_path_errors {
 7807            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7808                if let Some(path) = error.error_tag("path") {
 7809                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7810                }
 7811            } else {
 7812                workspace.show_error(&error, cx)
 7813            }
 7814        }
 7815    })?;
 7816
 7817    Ok(items.into_iter().map(|item| item?.ok()).collect())
 7818}
 7819
 7820fn serialize_remote_project(
 7821    connection_options: RemoteConnectionOptions,
 7822    paths: Vec<PathBuf>,
 7823    cx: &AsyncApp,
 7824) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7825    cx.background_spawn(async move {
 7826        let remote_connection_id = persistence::DB
 7827            .get_or_create_remote_connection(connection_options)
 7828            .await?;
 7829
 7830        let serialized_workspace =
 7831            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 7832
 7833        let workspace_id = if let Some(workspace_id) =
 7834            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7835        {
 7836            workspace_id
 7837        } else {
 7838            persistence::DB.next_id().await?
 7839        };
 7840
 7841        Ok((workspace_id, serialized_workspace))
 7842    })
 7843}
 7844
 7845pub fn join_in_room_project(
 7846    project_id: u64,
 7847    follow_user_id: u64,
 7848    app_state: Arc<AppState>,
 7849    cx: &mut App,
 7850) -> Task<Result<()>> {
 7851    let windows = cx.windows();
 7852    cx.spawn(async move |cx| {
 7853        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7854            window_handle
 7855                .downcast::<Workspace>()
 7856                .and_then(|window_handle| {
 7857                    window_handle
 7858                        .update(cx, |workspace, _window, cx| {
 7859                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7860                                Some(window_handle)
 7861                            } else {
 7862                                None
 7863                            }
 7864                        })
 7865                        .unwrap_or(None)
 7866                })
 7867        });
 7868
 7869        let workspace = if let Some(existing_workspace) = existing_workspace {
 7870            existing_workspace
 7871        } else {
 7872            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7873            let room = active_call
 7874                .read_with(cx, |call, _| call.room().cloned())?
 7875                .context("not in a call")?;
 7876            let project = room
 7877                .update(cx, |room, cx| {
 7878                    room.join_project(
 7879                        project_id,
 7880                        app_state.languages.clone(),
 7881                        app_state.fs.clone(),
 7882                        cx,
 7883                    )
 7884                })?
 7885                .await?;
 7886
 7887            let window_bounds_override = window_bounds_env_override();
 7888            cx.update(|cx| {
 7889                let mut options = (app_state.build_window_options)(None, cx);
 7890                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7891                cx.open_window(options, |window, cx| {
 7892                    cx.new(|cx| {
 7893                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7894                    })
 7895                })
 7896            })??
 7897        };
 7898
 7899        workspace.update(cx, |workspace, window, cx| {
 7900            cx.activate(true);
 7901            window.activate_window();
 7902
 7903            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7904                let follow_peer_id = room
 7905                    .read(cx)
 7906                    .remote_participants()
 7907                    .iter()
 7908                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7909                    .map(|(_, p)| p.peer_id)
 7910                    .or_else(|| {
 7911                        // If we couldn't follow the given user, follow the host instead.
 7912                        let collaborator = workspace
 7913                            .project()
 7914                            .read(cx)
 7915                            .collaborators()
 7916                            .values()
 7917                            .find(|collaborator| collaborator.is_host)?;
 7918                        Some(collaborator.peer_id)
 7919                    });
 7920
 7921                if let Some(follow_peer_id) = follow_peer_id {
 7922                    workspace.follow(follow_peer_id, window, cx);
 7923                }
 7924            }
 7925        })?;
 7926
 7927        anyhow::Ok(())
 7928    })
 7929}
 7930
 7931pub fn reload(cx: &mut App) {
 7932    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7933    let mut workspace_windows = cx
 7934        .windows()
 7935        .into_iter()
 7936        .filter_map(|window| window.downcast::<Workspace>())
 7937        .collect::<Vec<_>>();
 7938
 7939    // If multiple windows have unsaved changes, and need a save prompt,
 7940    // prompt in the active window before switching to a different window.
 7941    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7942
 7943    let mut prompt = None;
 7944    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7945        prompt = window
 7946            .update(cx, |_, window, cx| {
 7947                window.prompt(
 7948                    PromptLevel::Info,
 7949                    "Are you sure you want to restart?",
 7950                    None,
 7951                    &["Restart", "Cancel"],
 7952                    cx,
 7953                )
 7954            })
 7955            .ok();
 7956    }
 7957
 7958    cx.spawn(async move |cx| {
 7959        if let Some(prompt) = prompt {
 7960            let answer = prompt.await?;
 7961            if answer != 0 {
 7962                return Ok(());
 7963            }
 7964        }
 7965
 7966        // If the user cancels any save prompt, then keep the app open.
 7967        for window in workspace_windows {
 7968            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7969                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7970            }) && !should_close.await?
 7971            {
 7972                return Ok(());
 7973            }
 7974        }
 7975        cx.update(|cx| cx.restart())
 7976    })
 7977    .detach_and_log_err(cx);
 7978}
 7979
 7980fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7981    let mut parts = value.split(',');
 7982    let x: usize = parts.next()?.parse().ok()?;
 7983    let y: usize = parts.next()?.parse().ok()?;
 7984    Some(point(px(x as f32), px(y as f32)))
 7985}
 7986
 7987fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7988    let mut parts = value.split(',');
 7989    let width: usize = parts.next()?.parse().ok()?;
 7990    let height: usize = parts.next()?.parse().ok()?;
 7991    Some(size(px(width as f32), px(height as f32)))
 7992}
 7993
 7994/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7995pub fn client_side_decorations(
 7996    element: impl IntoElement,
 7997    window: &mut Window,
 7998    cx: &mut App,
 7999) -> Stateful<Div> {
 8000    const BORDER_SIZE: Pixels = px(1.0);
 8001    let decorations = window.window_decorations();
 8002
 8003    match decorations {
 8004        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 8005        Decorations::Server => window.set_client_inset(px(0.0)),
 8006    }
 8007
 8008    struct GlobalResizeEdge(ResizeEdge);
 8009    impl Global for GlobalResizeEdge {}
 8010
 8011    div()
 8012        .id("window-backdrop")
 8013        .bg(transparent_black())
 8014        .map(|div| match decorations {
 8015            Decorations::Server => div,
 8016            Decorations::Client { tiling, .. } => div
 8017                .when(!(tiling.top || tiling.right), |div| {
 8018                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8019                })
 8020                .when(!(tiling.top || tiling.left), |div| {
 8021                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8022                })
 8023                .when(!(tiling.bottom || tiling.right), |div| {
 8024                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8025                })
 8026                .when(!(tiling.bottom || tiling.left), |div| {
 8027                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8028                })
 8029                .when(!tiling.top, |div| {
 8030                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8031                })
 8032                .when(!tiling.bottom, |div| {
 8033                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8034                })
 8035                .when(!tiling.left, |div| {
 8036                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8037                })
 8038                .when(!tiling.right, |div| {
 8039                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8040                })
 8041                .on_mouse_move(move |e, window, cx| {
 8042                    let size = window.window_bounds().get_bounds().size;
 8043                    let pos = e.position;
 8044
 8045                    let new_edge =
 8046                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8047
 8048                    let edge = cx.try_global::<GlobalResizeEdge>();
 8049                    if new_edge != edge.map(|edge| edge.0) {
 8050                        window
 8051                            .window_handle()
 8052                            .update(cx, |workspace, _, cx| {
 8053                                cx.notify(workspace.entity_id());
 8054                            })
 8055                            .ok();
 8056                    }
 8057                })
 8058                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8059                    let size = window.window_bounds().get_bounds().size;
 8060                    let pos = e.position;
 8061
 8062                    let edge = match resize_edge(
 8063                        pos,
 8064                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8065                        size,
 8066                        tiling,
 8067                    ) {
 8068                        Some(value) => value,
 8069                        None => return,
 8070                    };
 8071
 8072                    window.start_window_resize(edge);
 8073                }),
 8074        })
 8075        .size_full()
 8076        .child(
 8077            div()
 8078                .cursor(CursorStyle::Arrow)
 8079                .map(|div| match decorations {
 8080                    Decorations::Server => div,
 8081                    Decorations::Client { tiling } => div
 8082                        .border_color(cx.theme().colors().border)
 8083                        .when(!(tiling.top || tiling.right), |div| {
 8084                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8085                        })
 8086                        .when(!(tiling.top || tiling.left), |div| {
 8087                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8088                        })
 8089                        .when(!(tiling.bottom || tiling.right), |div| {
 8090                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8091                        })
 8092                        .when(!(tiling.bottom || tiling.left), |div| {
 8093                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8094                        })
 8095                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8096                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8097                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8098                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8099                        .when(!tiling.is_tiled(), |div| {
 8100                            div.shadow(vec![gpui::BoxShadow {
 8101                                color: Hsla {
 8102                                    h: 0.,
 8103                                    s: 0.,
 8104                                    l: 0.,
 8105                                    a: 0.4,
 8106                                },
 8107                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8108                                spread_radius: px(0.),
 8109                                offset: point(px(0.0), px(0.0)),
 8110                            }])
 8111                        }),
 8112                })
 8113                .on_mouse_move(|_e, _, cx| {
 8114                    cx.stop_propagation();
 8115                })
 8116                .size_full()
 8117                .child(element),
 8118        )
 8119        .map(|div| match decorations {
 8120            Decorations::Server => div,
 8121            Decorations::Client { tiling, .. } => div.child(
 8122                canvas(
 8123                    |_bounds, window, _| {
 8124                        window.insert_hitbox(
 8125                            Bounds::new(
 8126                                point(px(0.0), px(0.0)),
 8127                                window.window_bounds().get_bounds().size,
 8128                            ),
 8129                            HitboxBehavior::Normal,
 8130                        )
 8131                    },
 8132                    move |_bounds, hitbox, window, cx| {
 8133                        let mouse = window.mouse_position();
 8134                        let size = window.window_bounds().get_bounds().size;
 8135                        let Some(edge) =
 8136                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8137                        else {
 8138                            return;
 8139                        };
 8140                        cx.set_global(GlobalResizeEdge(edge));
 8141                        window.set_cursor_style(
 8142                            match edge {
 8143                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8144                                ResizeEdge::Left | ResizeEdge::Right => {
 8145                                    CursorStyle::ResizeLeftRight
 8146                                }
 8147                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8148                                    CursorStyle::ResizeUpLeftDownRight
 8149                                }
 8150                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8151                                    CursorStyle::ResizeUpRightDownLeft
 8152                                }
 8153                            },
 8154                            &hitbox,
 8155                        );
 8156                    },
 8157                )
 8158                .size_full()
 8159                .absolute(),
 8160            ),
 8161        })
 8162}
 8163
 8164fn resize_edge(
 8165    pos: Point<Pixels>,
 8166    shadow_size: Pixels,
 8167    window_size: Size<Pixels>,
 8168    tiling: Tiling,
 8169) -> Option<ResizeEdge> {
 8170    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8171    if bounds.contains(&pos) {
 8172        return None;
 8173    }
 8174
 8175    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8176    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8177    if !tiling.top && top_left_bounds.contains(&pos) {
 8178        return Some(ResizeEdge::TopLeft);
 8179    }
 8180
 8181    let top_right_bounds = Bounds::new(
 8182        Point::new(window_size.width - corner_size.width, px(0.)),
 8183        corner_size,
 8184    );
 8185    if !tiling.top && top_right_bounds.contains(&pos) {
 8186        return Some(ResizeEdge::TopRight);
 8187    }
 8188
 8189    let bottom_left_bounds = Bounds::new(
 8190        Point::new(px(0.), window_size.height - corner_size.height),
 8191        corner_size,
 8192    );
 8193    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8194        return Some(ResizeEdge::BottomLeft);
 8195    }
 8196
 8197    let bottom_right_bounds = Bounds::new(
 8198        Point::new(
 8199            window_size.width - corner_size.width,
 8200            window_size.height - corner_size.height,
 8201        ),
 8202        corner_size,
 8203    );
 8204    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8205        return Some(ResizeEdge::BottomRight);
 8206    }
 8207
 8208    if !tiling.top && pos.y < shadow_size {
 8209        Some(ResizeEdge::Top)
 8210    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8211        Some(ResizeEdge::Bottom)
 8212    } else if !tiling.left && pos.x < shadow_size {
 8213        Some(ResizeEdge::Left)
 8214    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8215        Some(ResizeEdge::Right)
 8216    } else {
 8217        None
 8218    }
 8219}
 8220
 8221fn join_pane_into_active(
 8222    active_pane: &Entity<Pane>,
 8223    pane: &Entity<Pane>,
 8224    window: &mut Window,
 8225    cx: &mut App,
 8226) {
 8227    if pane == active_pane {
 8228    } else if pane.read(cx).items_len() == 0 {
 8229        pane.update(cx, |_, cx| {
 8230            cx.emit(pane::Event::Remove {
 8231                focus_on_pane: None,
 8232            });
 8233        })
 8234    } else {
 8235        move_all_items(pane, active_pane, window, cx);
 8236    }
 8237}
 8238
 8239fn move_all_items(
 8240    from_pane: &Entity<Pane>,
 8241    to_pane: &Entity<Pane>,
 8242    window: &mut Window,
 8243    cx: &mut App,
 8244) {
 8245    let destination_is_different = from_pane != to_pane;
 8246    let mut moved_items = 0;
 8247    for (item_ix, item_handle) in from_pane
 8248        .read(cx)
 8249        .items()
 8250        .enumerate()
 8251        .map(|(ix, item)| (ix, item.clone()))
 8252        .collect::<Vec<_>>()
 8253    {
 8254        let ix = item_ix - moved_items;
 8255        if destination_is_different {
 8256            // Close item from previous pane
 8257            from_pane.update(cx, |source, cx| {
 8258                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8259            });
 8260            moved_items += 1;
 8261        }
 8262
 8263        // This automatically removes duplicate items in the pane
 8264        to_pane.update(cx, |destination, cx| {
 8265            destination.add_item(item_handle, true, true, None, window, cx);
 8266            window.focus(&destination.focus_handle(cx))
 8267        });
 8268    }
 8269}
 8270
 8271pub fn move_item(
 8272    source: &Entity<Pane>,
 8273    destination: &Entity<Pane>,
 8274    item_id_to_move: EntityId,
 8275    destination_index: usize,
 8276    activate: bool,
 8277    window: &mut Window,
 8278    cx: &mut App,
 8279) {
 8280    let Some((item_ix, item_handle)) = source
 8281        .read(cx)
 8282        .items()
 8283        .enumerate()
 8284        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8285        .map(|(ix, item)| (ix, item.clone()))
 8286    else {
 8287        // Tab was closed during drag
 8288        return;
 8289    };
 8290
 8291    if source != destination {
 8292        // Close item from previous pane
 8293        source.update(cx, |source, cx| {
 8294            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8295        });
 8296    }
 8297
 8298    // This automatically removes duplicate items in the pane
 8299    destination.update(cx, |destination, cx| {
 8300        destination.add_item_inner(
 8301            item_handle,
 8302            activate,
 8303            activate,
 8304            activate,
 8305            Some(destination_index),
 8306            window,
 8307            cx,
 8308        );
 8309        if activate {
 8310            window.focus(&destination.focus_handle(cx))
 8311        }
 8312    });
 8313}
 8314
 8315pub fn move_active_item(
 8316    source: &Entity<Pane>,
 8317    destination: &Entity<Pane>,
 8318    focus_destination: bool,
 8319    close_if_empty: bool,
 8320    window: &mut Window,
 8321    cx: &mut App,
 8322) {
 8323    if source == destination {
 8324        return;
 8325    }
 8326    let Some(active_item) = source.read(cx).active_item() else {
 8327        return;
 8328    };
 8329    source.update(cx, |source_pane, cx| {
 8330        let item_id = active_item.item_id();
 8331        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8332        destination.update(cx, |target_pane, cx| {
 8333            target_pane.add_item(
 8334                active_item,
 8335                focus_destination,
 8336                focus_destination,
 8337                Some(target_pane.items_len()),
 8338                window,
 8339                cx,
 8340            );
 8341        });
 8342    });
 8343}
 8344
 8345pub fn clone_active_item(
 8346    workspace_id: Option<WorkspaceId>,
 8347    source: &Entity<Pane>,
 8348    destination: &Entity<Pane>,
 8349    focus_destination: bool,
 8350    window: &mut Window,
 8351    cx: &mut App,
 8352) {
 8353    if source == destination {
 8354        return;
 8355    }
 8356    let Some(active_item) = source.read(cx).active_item() else {
 8357        return;
 8358    };
 8359    if !active_item.can_split(cx) {
 8360        return;
 8361    }
 8362    let destination = destination.downgrade();
 8363    let task = active_item.clone_on_split(workspace_id, window, cx);
 8364    window
 8365        .spawn(cx, async move |cx| {
 8366            let Some(clone) = task.await else {
 8367                return;
 8368            };
 8369            destination
 8370                .update_in(cx, |target_pane, window, cx| {
 8371                    target_pane.add_item(
 8372                        clone,
 8373                        focus_destination,
 8374                        focus_destination,
 8375                        Some(target_pane.items_len()),
 8376                        window,
 8377                        cx,
 8378                    );
 8379                })
 8380                .log_err();
 8381        })
 8382        .detach();
 8383}
 8384
 8385#[derive(Debug)]
 8386pub struct WorkspacePosition {
 8387    pub window_bounds: Option<WindowBounds>,
 8388    pub display: Option<Uuid>,
 8389    pub centered_layout: bool,
 8390}
 8391
 8392pub fn remote_workspace_position_from_db(
 8393    connection_options: RemoteConnectionOptions,
 8394    paths_to_open: &[PathBuf],
 8395    cx: &App,
 8396) -> Task<Result<WorkspacePosition>> {
 8397    let paths = paths_to_open.to_vec();
 8398
 8399    cx.background_spawn(async move {
 8400        let remote_connection_id = persistence::DB
 8401            .get_or_create_remote_connection(connection_options)
 8402            .await
 8403            .context("fetching serialized ssh project")?;
 8404        let serialized_workspace =
 8405            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8406
 8407        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8408            (Some(WindowBounds::Windowed(bounds)), None)
 8409        } else {
 8410            let restorable_bounds = serialized_workspace
 8411                .as_ref()
 8412                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8413                .or_else(|| {
 8414                    let (display, window_bounds) = DB.last_window().log_err()?;
 8415                    Some((display?, window_bounds?))
 8416                });
 8417
 8418            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8419                (Some(serialized_status.0), Some(serialized_display))
 8420            } else {
 8421                (None, None)
 8422            }
 8423        };
 8424
 8425        let centered_layout = serialized_workspace
 8426            .as_ref()
 8427            .map(|w| w.centered_layout)
 8428            .unwrap_or(false);
 8429
 8430        Ok(WorkspacePosition {
 8431            window_bounds,
 8432            display,
 8433            centered_layout,
 8434        })
 8435    })
 8436}
 8437
 8438pub fn with_active_or_new_workspace(
 8439    cx: &mut App,
 8440    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8441) {
 8442    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8443        Some(workspace) => {
 8444            cx.defer(move |cx| {
 8445                workspace
 8446                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8447                    .log_err();
 8448            });
 8449        }
 8450        None => {
 8451            let app_state = AppState::global(cx);
 8452            if let Some(app_state) = app_state.upgrade() {
 8453                open_new(
 8454                    OpenOptions::default(),
 8455                    app_state,
 8456                    cx,
 8457                    move |workspace, window, cx| f(workspace, window, cx),
 8458                )
 8459                .detach_and_log_err(cx);
 8460            }
 8461        }
 8462    }
 8463}
 8464
 8465#[cfg(test)]
 8466mod tests {
 8467    use std::{cell::RefCell, rc::Rc};
 8468
 8469    use super::*;
 8470    use crate::{
 8471        dock::{PanelEvent, test::TestPanel},
 8472        item::{
 8473            ItemBufferKind, ItemEvent,
 8474            test::{TestItem, TestProjectItem},
 8475        },
 8476    };
 8477    use fs::FakeFs;
 8478    use gpui::{
 8479        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8480        UpdateGlobal, VisualTestContext, px,
 8481    };
 8482    use project::{Project, ProjectEntryId};
 8483    use serde_json::json;
 8484    use settings::SettingsStore;
 8485    use util::rel_path::rel_path;
 8486
 8487    #[gpui::test]
 8488    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8489        init_test(cx);
 8490
 8491        let fs = FakeFs::new(cx.executor());
 8492        let project = Project::test(fs, [], cx).await;
 8493        let (workspace, cx) =
 8494            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8495
 8496        // Adding an item with no ambiguity renders the tab without detail.
 8497        let item1 = cx.new(|cx| {
 8498            let mut item = TestItem::new(cx);
 8499            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8500            item
 8501        });
 8502        workspace.update_in(cx, |workspace, window, cx| {
 8503            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8504        });
 8505        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8506
 8507        // Adding an item that creates ambiguity increases the level of detail on
 8508        // both tabs.
 8509        let item2 = cx.new_window_entity(|_window, cx| {
 8510            let mut item = TestItem::new(cx);
 8511            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8512            item
 8513        });
 8514        workspace.update_in(cx, |workspace, window, cx| {
 8515            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8516        });
 8517        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8518        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8519
 8520        // Adding an item that creates ambiguity increases the level of detail only
 8521        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8522        // we stop at the highest detail available.
 8523        let item3 = cx.new(|cx| {
 8524            let mut item = TestItem::new(cx);
 8525            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8526            item
 8527        });
 8528        workspace.update_in(cx, |workspace, window, cx| {
 8529            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8530        });
 8531        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8532        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8533        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8534    }
 8535
 8536    #[gpui::test]
 8537    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8538        init_test(cx);
 8539
 8540        let fs = FakeFs::new(cx.executor());
 8541        fs.insert_tree(
 8542            "/root1",
 8543            json!({
 8544                "one.txt": "",
 8545                "two.txt": "",
 8546            }),
 8547        )
 8548        .await;
 8549        fs.insert_tree(
 8550            "/root2",
 8551            json!({
 8552                "three.txt": "",
 8553            }),
 8554        )
 8555        .await;
 8556
 8557        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8558        let (workspace, cx) =
 8559            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8560        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8561        let worktree_id = project.update(cx, |project, cx| {
 8562            project.worktrees(cx).next().unwrap().read(cx).id()
 8563        });
 8564
 8565        let item1 = cx.new(|cx| {
 8566            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8567        });
 8568        let item2 = cx.new(|cx| {
 8569            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8570        });
 8571
 8572        // Add an item to an empty pane
 8573        workspace.update_in(cx, |workspace, window, cx| {
 8574            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8575        });
 8576        project.update(cx, |project, cx| {
 8577            assert_eq!(
 8578                project.active_entry(),
 8579                project
 8580                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8581                    .map(|e| e.id)
 8582            );
 8583        });
 8584        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8585
 8586        // Add a second item to a non-empty pane
 8587        workspace.update_in(cx, |workspace, window, cx| {
 8588            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8589        });
 8590        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8591        project.update(cx, |project, cx| {
 8592            assert_eq!(
 8593                project.active_entry(),
 8594                project
 8595                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 8596                    .map(|e| e.id)
 8597            );
 8598        });
 8599
 8600        // Close the active item
 8601        pane.update_in(cx, |pane, window, cx| {
 8602            pane.close_active_item(&Default::default(), window, cx)
 8603        })
 8604        .await
 8605        .unwrap();
 8606        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8607        project.update(cx, |project, cx| {
 8608            assert_eq!(
 8609                project.active_entry(),
 8610                project
 8611                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8612                    .map(|e| e.id)
 8613            );
 8614        });
 8615
 8616        // Add a project folder
 8617        project
 8618            .update(cx, |project, cx| {
 8619                project.find_or_create_worktree("root2", true, cx)
 8620            })
 8621            .await
 8622            .unwrap();
 8623        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8624
 8625        // Remove a project folder
 8626        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8627        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8628    }
 8629
 8630    #[gpui::test]
 8631    async fn test_close_window(cx: &mut TestAppContext) {
 8632        init_test(cx);
 8633
 8634        let fs = FakeFs::new(cx.executor());
 8635        fs.insert_tree("/root", json!({ "one": "" })).await;
 8636
 8637        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8638        let (workspace, cx) =
 8639            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8640
 8641        // When there are no dirty items, there's nothing to do.
 8642        let item1 = cx.new(TestItem::new);
 8643        workspace.update_in(cx, |w, window, cx| {
 8644            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8645        });
 8646        let task = workspace.update_in(cx, |w, window, cx| {
 8647            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8648        });
 8649        assert!(task.await.unwrap());
 8650
 8651        // When there are dirty untitled items, prompt to save each one. If the user
 8652        // cancels any prompt, then abort.
 8653        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8654        let item3 = cx.new(|cx| {
 8655            TestItem::new(cx)
 8656                .with_dirty(true)
 8657                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8658        });
 8659        workspace.update_in(cx, |w, window, cx| {
 8660            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8661            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8662        });
 8663        let task = workspace.update_in(cx, |w, window, cx| {
 8664            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8665        });
 8666        cx.executor().run_until_parked();
 8667        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8668        cx.executor().run_until_parked();
 8669        assert!(!cx.has_pending_prompt());
 8670        assert!(!task.await.unwrap());
 8671    }
 8672
 8673    #[gpui::test]
 8674    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8675        init_test(cx);
 8676
 8677        // Register TestItem as a serializable item
 8678        cx.update(|cx| {
 8679            register_serializable_item::<TestItem>(cx);
 8680        });
 8681
 8682        let fs = FakeFs::new(cx.executor());
 8683        fs.insert_tree("/root", json!({ "one": "" })).await;
 8684
 8685        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8686        let (workspace, cx) =
 8687            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8688
 8689        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8690        let item1 = cx.new(|cx| {
 8691            TestItem::new(cx)
 8692                .with_dirty(true)
 8693                .with_serialize(|| Some(Task::ready(Ok(()))))
 8694        });
 8695        let item2 = cx.new(|cx| {
 8696            TestItem::new(cx)
 8697                .with_dirty(true)
 8698                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8699                .with_serialize(|| Some(Task::ready(Ok(()))))
 8700        });
 8701        workspace.update_in(cx, |w, window, cx| {
 8702            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8703            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8704        });
 8705        let task = workspace.update_in(cx, |w, window, cx| {
 8706            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8707        });
 8708        assert!(task.await.unwrap());
 8709    }
 8710
 8711    #[gpui::test]
 8712    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8713        init_test(cx);
 8714
 8715        let fs = FakeFs::new(cx.executor());
 8716
 8717        let project = Project::test(fs, None, cx).await;
 8718        let (workspace, cx) =
 8719            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8720
 8721        let item1 = cx.new(|cx| {
 8722            TestItem::new(cx)
 8723                .with_dirty(true)
 8724                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8725        });
 8726        let item2 = cx.new(|cx| {
 8727            TestItem::new(cx)
 8728                .with_dirty(true)
 8729                .with_conflict(true)
 8730                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8731        });
 8732        let item3 = cx.new(|cx| {
 8733            TestItem::new(cx)
 8734                .with_dirty(true)
 8735                .with_conflict(true)
 8736                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8737        });
 8738        let item4 = cx.new(|cx| {
 8739            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8740                let project_item = TestProjectItem::new_untitled(cx);
 8741                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8742                project_item
 8743            }])
 8744        });
 8745        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8746            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8747            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8748            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8749            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8750            workspace.active_pane().clone()
 8751        });
 8752
 8753        let close_items = pane.update_in(cx, |pane, window, cx| {
 8754            pane.activate_item(1, true, true, window, cx);
 8755            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8756            let item1_id = item1.item_id();
 8757            let item3_id = item3.item_id();
 8758            let item4_id = item4.item_id();
 8759            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8760                [item1_id, item3_id, item4_id].contains(&id)
 8761            })
 8762        });
 8763        cx.executor().run_until_parked();
 8764
 8765        assert!(cx.has_pending_prompt());
 8766        cx.simulate_prompt_answer("Save all");
 8767
 8768        cx.executor().run_until_parked();
 8769
 8770        // Item 1 is saved. There's a prompt to save item 3.
 8771        pane.update(cx, |pane, cx| {
 8772            assert_eq!(item1.read(cx).save_count, 1);
 8773            assert_eq!(item1.read(cx).save_as_count, 0);
 8774            assert_eq!(item1.read(cx).reload_count, 0);
 8775            assert_eq!(pane.items_len(), 3);
 8776            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8777        });
 8778        assert!(cx.has_pending_prompt());
 8779
 8780        // Cancel saving item 3.
 8781        cx.simulate_prompt_answer("Discard");
 8782        cx.executor().run_until_parked();
 8783
 8784        // Item 3 is reloaded. There's a prompt to save item 4.
 8785        pane.update(cx, |pane, cx| {
 8786            assert_eq!(item3.read(cx).save_count, 0);
 8787            assert_eq!(item3.read(cx).save_as_count, 0);
 8788            assert_eq!(item3.read(cx).reload_count, 1);
 8789            assert_eq!(pane.items_len(), 2);
 8790            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8791        });
 8792
 8793        // There's a prompt for a path for item 4.
 8794        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8795        close_items.await.unwrap();
 8796
 8797        // The requested items are closed.
 8798        pane.update(cx, |pane, cx| {
 8799            assert_eq!(item4.read(cx).save_count, 0);
 8800            assert_eq!(item4.read(cx).save_as_count, 1);
 8801            assert_eq!(item4.read(cx).reload_count, 0);
 8802            assert_eq!(pane.items_len(), 1);
 8803            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8804        });
 8805    }
 8806
 8807    #[gpui::test]
 8808    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8809        init_test(cx);
 8810
 8811        let fs = FakeFs::new(cx.executor());
 8812        let project = Project::test(fs, [], cx).await;
 8813        let (workspace, cx) =
 8814            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8815
 8816        // Create several workspace items with single project entries, and two
 8817        // workspace items with multiple project entries.
 8818        let single_entry_items = (0..=4)
 8819            .map(|project_entry_id| {
 8820                cx.new(|cx| {
 8821                    TestItem::new(cx)
 8822                        .with_dirty(true)
 8823                        .with_project_items(&[dirty_project_item(
 8824                            project_entry_id,
 8825                            &format!("{project_entry_id}.txt"),
 8826                            cx,
 8827                        )])
 8828                })
 8829            })
 8830            .collect::<Vec<_>>();
 8831        let item_2_3 = cx.new(|cx| {
 8832            TestItem::new(cx)
 8833                .with_dirty(true)
 8834                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8835                .with_project_items(&[
 8836                    single_entry_items[2].read(cx).project_items[0].clone(),
 8837                    single_entry_items[3].read(cx).project_items[0].clone(),
 8838                ])
 8839        });
 8840        let item_3_4 = cx.new(|cx| {
 8841            TestItem::new(cx)
 8842                .with_dirty(true)
 8843                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8844                .with_project_items(&[
 8845                    single_entry_items[3].read(cx).project_items[0].clone(),
 8846                    single_entry_items[4].read(cx).project_items[0].clone(),
 8847                ])
 8848        });
 8849
 8850        // Create two panes that contain the following project entries:
 8851        //   left pane:
 8852        //     multi-entry items:   (2, 3)
 8853        //     single-entry items:  0, 2, 3, 4
 8854        //   right pane:
 8855        //     single-entry items:  4, 1
 8856        //     multi-entry items:   (3, 4)
 8857        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8858            let left_pane = workspace.active_pane().clone();
 8859            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8860            workspace.add_item_to_active_pane(
 8861                single_entry_items[0].boxed_clone(),
 8862                None,
 8863                true,
 8864                window,
 8865                cx,
 8866            );
 8867            workspace.add_item_to_active_pane(
 8868                single_entry_items[2].boxed_clone(),
 8869                None,
 8870                true,
 8871                window,
 8872                cx,
 8873            );
 8874            workspace.add_item_to_active_pane(
 8875                single_entry_items[3].boxed_clone(),
 8876                None,
 8877                true,
 8878                window,
 8879                cx,
 8880            );
 8881            workspace.add_item_to_active_pane(
 8882                single_entry_items[4].boxed_clone(),
 8883                None,
 8884                true,
 8885                window,
 8886                cx,
 8887            );
 8888
 8889            let right_pane =
 8890                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 8891
 8892            let boxed_clone = single_entry_items[1].boxed_clone();
 8893            let right_pane = window.spawn(cx, async move |cx| {
 8894                right_pane.await.inspect(|right_pane| {
 8895                    right_pane
 8896                        .update_in(cx, |pane, window, cx| {
 8897                            pane.add_item(boxed_clone, true, true, None, window, cx);
 8898                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8899                        })
 8900                        .unwrap();
 8901                })
 8902            });
 8903
 8904            (left_pane, right_pane)
 8905        });
 8906        let right_pane = right_pane.await.unwrap();
 8907        cx.focus(&right_pane);
 8908
 8909        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8910            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8911                .unwrap()
 8912        });
 8913        cx.executor().run_until_parked();
 8914
 8915        let msg = cx.pending_prompt().unwrap().0;
 8916        assert!(msg.contains("1.txt"));
 8917        assert!(!msg.contains("2.txt"));
 8918        assert!(!msg.contains("3.txt"));
 8919        assert!(!msg.contains("4.txt"));
 8920
 8921        cx.simulate_prompt_answer("Cancel");
 8922        close.await;
 8923
 8924        left_pane
 8925            .update_in(cx, |left_pane, window, cx| {
 8926                left_pane.close_item_by_id(
 8927                    single_entry_items[3].entity_id(),
 8928                    SaveIntent::Skip,
 8929                    window,
 8930                    cx,
 8931                )
 8932            })
 8933            .await
 8934            .unwrap();
 8935
 8936        close = right_pane.update_in(cx, |pane, window, cx| {
 8937            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8938                .unwrap()
 8939        });
 8940        cx.executor().run_until_parked();
 8941
 8942        let details = cx.pending_prompt().unwrap().1;
 8943        assert!(details.contains("1.txt"));
 8944        assert!(!details.contains("2.txt"));
 8945        assert!(details.contains("3.txt"));
 8946        // ideally this assertion could be made, but today we can only
 8947        // save whole items not project items, so the orphaned item 3 causes
 8948        // 4 to be saved too.
 8949        // assert!(!details.contains("4.txt"));
 8950
 8951        cx.simulate_prompt_answer("Save all");
 8952
 8953        cx.executor().run_until_parked();
 8954        close.await;
 8955        right_pane.read_with(cx, |pane, _| {
 8956            assert_eq!(pane.items_len(), 0);
 8957        });
 8958    }
 8959
 8960    #[gpui::test]
 8961    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8962        init_test(cx);
 8963
 8964        let fs = FakeFs::new(cx.executor());
 8965        let project = Project::test(fs, [], cx).await;
 8966        let (workspace, cx) =
 8967            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8968        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8969
 8970        let item = cx.new(|cx| {
 8971            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8972        });
 8973        let item_id = item.entity_id();
 8974        workspace.update_in(cx, |workspace, window, cx| {
 8975            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8976        });
 8977
 8978        // Autosave on window change.
 8979        item.update(cx, |item, cx| {
 8980            SettingsStore::update_global(cx, |settings, cx| {
 8981                settings.update_user_settings(cx, |settings| {
 8982                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 8983                })
 8984            });
 8985            item.is_dirty = true;
 8986        });
 8987
 8988        // Deactivating the window saves the file.
 8989        cx.deactivate_window();
 8990        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8991
 8992        // Re-activating the window doesn't save the file.
 8993        cx.update(|window, _| window.activate_window());
 8994        cx.executor().run_until_parked();
 8995        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8996
 8997        // Autosave on focus change.
 8998        item.update_in(cx, |item, window, cx| {
 8999            cx.focus_self(window);
 9000            SettingsStore::update_global(cx, |settings, cx| {
 9001                settings.update_user_settings(cx, |settings| {
 9002                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9003                })
 9004            });
 9005            item.is_dirty = true;
 9006        });
 9007        // Blurring the item saves the file.
 9008        item.update_in(cx, |_, window, _| window.blur());
 9009        cx.executor().run_until_parked();
 9010        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 9011
 9012        // Deactivating the window still saves the file.
 9013        item.update_in(cx, |item, window, cx| {
 9014            cx.focus_self(window);
 9015            item.is_dirty = true;
 9016        });
 9017        cx.deactivate_window();
 9018        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 9019
 9020        // Autosave after delay.
 9021        item.update(cx, |item, cx| {
 9022            SettingsStore::update_global(cx, |settings, cx| {
 9023                settings.update_user_settings(cx, |settings| {
 9024                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 9025                        milliseconds: 500.into(),
 9026                    });
 9027                })
 9028            });
 9029            item.is_dirty = true;
 9030            cx.emit(ItemEvent::Edit);
 9031        });
 9032
 9033        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 9034        cx.executor().advance_clock(Duration::from_millis(250));
 9035        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 9036
 9037        // After delay expires, the file is saved.
 9038        cx.executor().advance_clock(Duration::from_millis(250));
 9039        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9040
 9041        // Autosave after delay, should save earlier than delay if tab is closed
 9042        item.update(cx, |item, cx| {
 9043            item.is_dirty = true;
 9044            cx.emit(ItemEvent::Edit);
 9045        });
 9046        cx.executor().advance_clock(Duration::from_millis(250));
 9047        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9048
 9049        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9050        pane.update_in(cx, |pane, window, cx| {
 9051            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9052        })
 9053        .await
 9054        .unwrap();
 9055        assert!(!cx.has_pending_prompt());
 9056        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9057
 9058        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9059        workspace.update_in(cx, |workspace, window, cx| {
 9060            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9061        });
 9062        item.update_in(cx, |item, _window, cx| {
 9063            item.is_dirty = true;
 9064            for project_item in &mut item.project_items {
 9065                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9066            }
 9067        });
 9068        cx.run_until_parked();
 9069        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9070
 9071        // Autosave on focus change, ensuring closing the tab counts as such.
 9072        item.update(cx, |item, cx| {
 9073            SettingsStore::update_global(cx, |settings, cx| {
 9074                settings.update_user_settings(cx, |settings| {
 9075                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9076                })
 9077            });
 9078            item.is_dirty = true;
 9079            for project_item in &mut item.project_items {
 9080                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9081            }
 9082        });
 9083
 9084        pane.update_in(cx, |pane, window, cx| {
 9085            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9086        })
 9087        .await
 9088        .unwrap();
 9089        assert!(!cx.has_pending_prompt());
 9090        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9091
 9092        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9093        workspace.update_in(cx, |workspace, window, cx| {
 9094            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9095        });
 9096        item.update_in(cx, |item, window, cx| {
 9097            item.project_items[0].update(cx, |item, _| {
 9098                item.entry_id = None;
 9099            });
 9100            item.is_dirty = true;
 9101            window.blur();
 9102        });
 9103        cx.run_until_parked();
 9104        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9105
 9106        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9107        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9108            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9109        });
 9110        cx.run_until_parked();
 9111        assert!(cx.has_pending_prompt());
 9112        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9113    }
 9114
 9115    #[gpui::test]
 9116    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9117        init_test(cx);
 9118
 9119        let fs = FakeFs::new(cx.executor());
 9120
 9121        let project = Project::test(fs, [], cx).await;
 9122        let (workspace, cx) =
 9123            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9124
 9125        let item = cx.new(|cx| {
 9126            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9127        });
 9128        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9129        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9130        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9131
 9132        workspace.update_in(cx, |workspace, window, cx| {
 9133            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9134            let toolbar_notification_count = toolbar_notify_count.clone();
 9135            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9136                *toolbar_notification_count.borrow_mut() += 1
 9137            })
 9138            .detach();
 9139        });
 9140
 9141        pane.read_with(cx, |pane, _| {
 9142            assert!(!pane.can_navigate_backward());
 9143            assert!(!pane.can_navigate_forward());
 9144        });
 9145
 9146        item.update_in(cx, |item, _, cx| {
 9147            item.set_state("one".to_string(), cx);
 9148        });
 9149
 9150        // Toolbar must be notified to re-render the navigation buttons
 9151        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9152
 9153        pane.read_with(cx, |pane, _| {
 9154            assert!(pane.can_navigate_backward());
 9155            assert!(!pane.can_navigate_forward());
 9156        });
 9157
 9158        workspace
 9159            .update_in(cx, |workspace, window, cx| {
 9160                workspace.go_back(pane.downgrade(), window, cx)
 9161            })
 9162            .await
 9163            .unwrap();
 9164
 9165        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9166        pane.read_with(cx, |pane, _| {
 9167            assert!(!pane.can_navigate_backward());
 9168            assert!(pane.can_navigate_forward());
 9169        });
 9170    }
 9171
 9172    #[gpui::test]
 9173    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9174        init_test(cx);
 9175        let fs = FakeFs::new(cx.executor());
 9176
 9177        let project = Project::test(fs, [], cx).await;
 9178        let (workspace, cx) =
 9179            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9180
 9181        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9182            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9183            workspace.add_panel(panel.clone(), window, cx);
 9184
 9185            workspace
 9186                .right_dock()
 9187                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9188
 9189            panel
 9190        });
 9191
 9192        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9193        pane.update_in(cx, |pane, window, cx| {
 9194            let item = cx.new(TestItem::new);
 9195            pane.add_item(Box::new(item), true, true, None, window, cx);
 9196        });
 9197
 9198        // Transfer focus from center to panel
 9199        workspace.update_in(cx, |workspace, window, cx| {
 9200            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9201        });
 9202
 9203        workspace.update_in(cx, |workspace, window, cx| {
 9204            assert!(workspace.right_dock().read(cx).is_open());
 9205            assert!(!panel.is_zoomed(window, cx));
 9206            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9207        });
 9208
 9209        // Transfer focus from panel to center
 9210        workspace.update_in(cx, |workspace, window, cx| {
 9211            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9212        });
 9213
 9214        workspace.update_in(cx, |workspace, window, cx| {
 9215            assert!(workspace.right_dock().read(cx).is_open());
 9216            assert!(!panel.is_zoomed(window, cx));
 9217            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9218        });
 9219
 9220        // Close the dock
 9221        workspace.update_in(cx, |workspace, window, cx| {
 9222            workspace.toggle_dock(DockPosition::Right, window, cx);
 9223        });
 9224
 9225        workspace.update_in(cx, |workspace, window, cx| {
 9226            assert!(!workspace.right_dock().read(cx).is_open());
 9227            assert!(!panel.is_zoomed(window, cx));
 9228            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9229        });
 9230
 9231        // Open the dock
 9232        workspace.update_in(cx, |workspace, window, cx| {
 9233            workspace.toggle_dock(DockPosition::Right, window, cx);
 9234        });
 9235
 9236        workspace.update_in(cx, |workspace, window, cx| {
 9237            assert!(workspace.right_dock().read(cx).is_open());
 9238            assert!(!panel.is_zoomed(window, cx));
 9239            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9240        });
 9241
 9242        // Focus and zoom panel
 9243        panel.update_in(cx, |panel, window, cx| {
 9244            cx.focus_self(window);
 9245            panel.set_zoomed(true, window, cx)
 9246        });
 9247
 9248        workspace.update_in(cx, |workspace, window, cx| {
 9249            assert!(workspace.right_dock().read(cx).is_open());
 9250            assert!(panel.is_zoomed(window, cx));
 9251            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9252        });
 9253
 9254        // Transfer focus to the center closes the dock
 9255        workspace.update_in(cx, |workspace, window, cx| {
 9256            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9257        });
 9258
 9259        workspace.update_in(cx, |workspace, window, cx| {
 9260            assert!(!workspace.right_dock().read(cx).is_open());
 9261            assert!(panel.is_zoomed(window, cx));
 9262            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9263        });
 9264
 9265        // Transferring focus back to the panel keeps it zoomed
 9266        workspace.update_in(cx, |workspace, window, cx| {
 9267            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9268        });
 9269
 9270        workspace.update_in(cx, |workspace, window, cx| {
 9271            assert!(workspace.right_dock().read(cx).is_open());
 9272            assert!(panel.is_zoomed(window, cx));
 9273            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9274        });
 9275
 9276        // Close the dock while it is zoomed
 9277        workspace.update_in(cx, |workspace, window, cx| {
 9278            workspace.toggle_dock(DockPosition::Right, window, cx)
 9279        });
 9280
 9281        workspace.update_in(cx, |workspace, window, cx| {
 9282            assert!(!workspace.right_dock().read(cx).is_open());
 9283            assert!(panel.is_zoomed(window, cx));
 9284            assert!(workspace.zoomed.is_none());
 9285            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9286        });
 9287
 9288        // Opening the dock, when it's zoomed, retains focus
 9289        workspace.update_in(cx, |workspace, window, cx| {
 9290            workspace.toggle_dock(DockPosition::Right, window, cx)
 9291        });
 9292
 9293        workspace.update_in(cx, |workspace, window, cx| {
 9294            assert!(workspace.right_dock().read(cx).is_open());
 9295            assert!(panel.is_zoomed(window, cx));
 9296            assert!(workspace.zoomed.is_some());
 9297            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9298        });
 9299
 9300        // Unzoom and close the panel, zoom the active pane.
 9301        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9302        workspace.update_in(cx, |workspace, window, cx| {
 9303            workspace.toggle_dock(DockPosition::Right, window, cx)
 9304        });
 9305        pane.update_in(cx, |pane, window, cx| {
 9306            pane.toggle_zoom(&Default::default(), window, cx)
 9307        });
 9308
 9309        // Opening a dock unzooms the pane.
 9310        workspace.update_in(cx, |workspace, window, cx| {
 9311            workspace.toggle_dock(DockPosition::Right, window, cx)
 9312        });
 9313        workspace.update_in(cx, |workspace, window, cx| {
 9314            let pane = pane.read(cx);
 9315            assert!(!pane.is_zoomed());
 9316            assert!(!pane.focus_handle(cx).is_focused(window));
 9317            assert!(workspace.right_dock().read(cx).is_open());
 9318            assert!(workspace.zoomed.is_none());
 9319        });
 9320    }
 9321
 9322    #[gpui::test]
 9323    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
 9324        init_test(cx);
 9325        let fs = FakeFs::new(cx.executor());
 9326
 9327        let project = Project::test(fs, [], cx).await;
 9328        let (workspace, cx) =
 9329            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9330        workspace.update_in(cx, |workspace, window, cx| {
 9331            // Open two docks
 9332            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9333            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9334
 9335            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9336            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9337
 9338            assert!(left_dock.read(cx).is_open());
 9339            assert!(right_dock.read(cx).is_open());
 9340        });
 9341
 9342        workspace.update_in(cx, |workspace, window, cx| {
 9343            // Toggle all docks - should close both
 9344            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9345
 9346            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9347            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9348            assert!(!left_dock.read(cx).is_open());
 9349            assert!(!right_dock.read(cx).is_open());
 9350        });
 9351
 9352        workspace.update_in(cx, |workspace, window, cx| {
 9353            // Toggle again - should reopen both
 9354            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9355
 9356            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9357            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9358            assert!(left_dock.read(cx).is_open());
 9359            assert!(right_dock.read(cx).is_open());
 9360        });
 9361    }
 9362
 9363    #[gpui::test]
 9364    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
 9365        init_test(cx);
 9366        let fs = FakeFs::new(cx.executor());
 9367
 9368        let project = Project::test(fs, [], cx).await;
 9369        let (workspace, cx) =
 9370            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9371        workspace.update_in(cx, |workspace, window, cx| {
 9372            // Open two docks
 9373            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9374            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9375
 9376            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9377            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9378
 9379            assert!(left_dock.read(cx).is_open());
 9380            assert!(right_dock.read(cx).is_open());
 9381        });
 9382
 9383        workspace.update_in(cx, |workspace, window, cx| {
 9384            // Close them manually
 9385            workspace.toggle_dock(DockPosition::Left, window, cx);
 9386            workspace.toggle_dock(DockPosition::Right, window, cx);
 9387
 9388            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9389            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9390            assert!(!left_dock.read(cx).is_open());
 9391            assert!(!right_dock.read(cx).is_open());
 9392        });
 9393
 9394        workspace.update_in(cx, |workspace, window, cx| {
 9395            // Toggle all docks - only last closed (right dock) should reopen
 9396            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9397
 9398            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9399            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9400            assert!(!left_dock.read(cx).is_open());
 9401            assert!(right_dock.read(cx).is_open());
 9402        });
 9403    }
 9404
 9405    #[gpui::test]
 9406    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
 9407        init_test(cx);
 9408        let fs = FakeFs::new(cx.executor());
 9409        let project = Project::test(fs, [], cx).await;
 9410        let (workspace, cx) =
 9411            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9412
 9413        // Open two docks (left and right) with one panel each
 9414        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
 9415            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9416            workspace.add_panel(left_panel.clone(), window, cx);
 9417
 9418            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9419            workspace.add_panel(right_panel.clone(), window, cx);
 9420
 9421            workspace.toggle_dock(DockPosition::Left, window, cx);
 9422            workspace.toggle_dock(DockPosition::Right, window, cx);
 9423
 9424            // Verify initial state
 9425            assert!(
 9426                workspace.left_dock().read(cx).is_open(),
 9427                "Left dock should be open"
 9428            );
 9429            assert_eq!(
 9430                workspace
 9431                    .left_dock()
 9432                    .read(cx)
 9433                    .visible_panel()
 9434                    .unwrap()
 9435                    .panel_id(),
 9436                left_panel.panel_id(),
 9437                "Left panel should be visible in left dock"
 9438            );
 9439            assert!(
 9440                workspace.right_dock().read(cx).is_open(),
 9441                "Right dock should be open"
 9442            );
 9443            assert_eq!(
 9444                workspace
 9445                    .right_dock()
 9446                    .read(cx)
 9447                    .visible_panel()
 9448                    .unwrap()
 9449                    .panel_id(),
 9450                right_panel.panel_id(),
 9451                "Right panel should be visible in right dock"
 9452            );
 9453            assert!(
 9454                !workspace.bottom_dock().read(cx).is_open(),
 9455                "Bottom dock should be closed"
 9456            );
 9457
 9458            (left_panel, right_panel)
 9459        });
 9460
 9461        // Focus the left panel and move it to the next position (bottom dock)
 9462        workspace.update_in(cx, |workspace, window, cx| {
 9463            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
 9464            assert!(
 9465                left_panel.read(cx).focus_handle(cx).is_focused(window),
 9466                "Left panel should be focused"
 9467            );
 9468        });
 9469
 9470        cx.dispatch_action(MoveFocusedPanelToNextPosition);
 9471
 9472        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
 9473        workspace.update(cx, |workspace, cx| {
 9474            assert!(
 9475                !workspace.left_dock().read(cx).is_open(),
 9476                "Left dock should be closed"
 9477            );
 9478            assert!(
 9479                workspace.bottom_dock().read(cx).is_open(),
 9480                "Bottom dock should now be open"
 9481            );
 9482            assert_eq!(
 9483                left_panel.read(cx).position,
 9484                DockPosition::Bottom,
 9485                "Left panel should now be in the bottom dock"
 9486            );
 9487            assert_eq!(
 9488                workspace
 9489                    .bottom_dock()
 9490                    .read(cx)
 9491                    .visible_panel()
 9492                    .unwrap()
 9493                    .panel_id(),
 9494                left_panel.panel_id(),
 9495                "Left panel should be the visible panel in the bottom dock"
 9496            );
 9497        });
 9498
 9499        // Toggle all docks off
 9500        workspace.update_in(cx, |workspace, window, cx| {
 9501            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9502            assert!(
 9503                !workspace.left_dock().read(cx).is_open(),
 9504                "Left dock should be closed"
 9505            );
 9506            assert!(
 9507                !workspace.right_dock().read(cx).is_open(),
 9508                "Right dock should be closed"
 9509            );
 9510            assert!(
 9511                !workspace.bottom_dock().read(cx).is_open(),
 9512                "Bottom dock should be closed"
 9513            );
 9514        });
 9515
 9516        // Toggle all docks back on and verify positions are restored
 9517        workspace.update_in(cx, |workspace, window, cx| {
 9518            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9519            assert!(
 9520                !workspace.left_dock().read(cx).is_open(),
 9521                "Left dock should remain closed"
 9522            );
 9523            assert!(
 9524                workspace.right_dock().read(cx).is_open(),
 9525                "Right dock should remain open"
 9526            );
 9527            assert!(
 9528                workspace.bottom_dock().read(cx).is_open(),
 9529                "Bottom dock should remain open"
 9530            );
 9531            assert_eq!(
 9532                left_panel.read(cx).position,
 9533                DockPosition::Bottom,
 9534                "Left panel should remain in the bottom dock"
 9535            );
 9536            assert_eq!(
 9537                right_panel.read(cx).position,
 9538                DockPosition::Right,
 9539                "Right panel should remain in the right dock"
 9540            );
 9541            assert_eq!(
 9542                workspace
 9543                    .bottom_dock()
 9544                    .read(cx)
 9545                    .visible_panel()
 9546                    .unwrap()
 9547                    .panel_id(),
 9548                left_panel.panel_id(),
 9549                "Left panel should be the visible panel in the right dock"
 9550            );
 9551        });
 9552    }
 9553
 9554    #[gpui::test]
 9555    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 9556        init_test(cx);
 9557
 9558        let fs = FakeFs::new(cx.executor());
 9559
 9560        let project = Project::test(fs, None, cx).await;
 9561        let (workspace, cx) =
 9562            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9563
 9564        // Let's arrange the panes like this:
 9565        //
 9566        // +-----------------------+
 9567        // |         top           |
 9568        // +------+--------+-------+
 9569        // | left | center | right |
 9570        // +------+--------+-------+
 9571        // |        bottom         |
 9572        // +-----------------------+
 9573
 9574        let top_item = cx.new(|cx| {
 9575            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 9576        });
 9577        let bottom_item = cx.new(|cx| {
 9578            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 9579        });
 9580        let left_item = cx.new(|cx| {
 9581            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 9582        });
 9583        let right_item = cx.new(|cx| {
 9584            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 9585        });
 9586        let center_item = cx.new(|cx| {
 9587            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 9588        });
 9589
 9590        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9591            let top_pane_id = workspace.active_pane().entity_id();
 9592            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 9593            workspace.split_pane(
 9594                workspace.active_pane().clone(),
 9595                SplitDirection::Down,
 9596                window,
 9597                cx,
 9598            );
 9599            top_pane_id
 9600        });
 9601        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9602            let bottom_pane_id = workspace.active_pane().entity_id();
 9603            workspace.add_item_to_active_pane(
 9604                Box::new(bottom_item.clone()),
 9605                None,
 9606                false,
 9607                window,
 9608                cx,
 9609            );
 9610            workspace.split_pane(
 9611                workspace.active_pane().clone(),
 9612                SplitDirection::Up,
 9613                window,
 9614                cx,
 9615            );
 9616            bottom_pane_id
 9617        });
 9618        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9619            let left_pane_id = workspace.active_pane().entity_id();
 9620            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 9621            workspace.split_pane(
 9622                workspace.active_pane().clone(),
 9623                SplitDirection::Right,
 9624                window,
 9625                cx,
 9626            );
 9627            left_pane_id
 9628        });
 9629        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9630            let right_pane_id = workspace.active_pane().entity_id();
 9631            workspace.add_item_to_active_pane(
 9632                Box::new(right_item.clone()),
 9633                None,
 9634                false,
 9635                window,
 9636                cx,
 9637            );
 9638            workspace.split_pane(
 9639                workspace.active_pane().clone(),
 9640                SplitDirection::Left,
 9641                window,
 9642                cx,
 9643            );
 9644            right_pane_id
 9645        });
 9646        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9647            let center_pane_id = workspace.active_pane().entity_id();
 9648            workspace.add_item_to_active_pane(
 9649                Box::new(center_item.clone()),
 9650                None,
 9651                false,
 9652                window,
 9653                cx,
 9654            );
 9655            center_pane_id
 9656        });
 9657        cx.executor().run_until_parked();
 9658
 9659        workspace.update_in(cx, |workspace, window, cx| {
 9660            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9661
 9662            // Join into next from center pane into right
 9663            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9664        });
 9665
 9666        workspace.update_in(cx, |workspace, window, cx| {
 9667            let active_pane = workspace.active_pane();
 9668            assert_eq!(right_pane_id, active_pane.entity_id());
 9669            assert_eq!(2, active_pane.read(cx).items_len());
 9670            let item_ids_in_pane =
 9671                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9672            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9673            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9674
 9675            // Join into next from right pane into bottom
 9676            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9677        });
 9678
 9679        workspace.update_in(cx, |workspace, window, cx| {
 9680            let active_pane = workspace.active_pane();
 9681            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9682            assert_eq!(3, active_pane.read(cx).items_len());
 9683            let item_ids_in_pane =
 9684                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9685            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9686            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9687            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9688
 9689            // Join into next from bottom pane into left
 9690            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9691        });
 9692
 9693        workspace.update_in(cx, |workspace, window, cx| {
 9694            let active_pane = workspace.active_pane();
 9695            assert_eq!(left_pane_id, active_pane.entity_id());
 9696            assert_eq!(4, active_pane.read(cx).items_len());
 9697            let item_ids_in_pane =
 9698                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9699            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9700            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9701            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9702            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9703
 9704            // Join into next from left pane into top
 9705            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9706        });
 9707
 9708        workspace.update_in(cx, |workspace, window, cx| {
 9709            let active_pane = workspace.active_pane();
 9710            assert_eq!(top_pane_id, active_pane.entity_id());
 9711            assert_eq!(5, active_pane.read(cx).items_len());
 9712            let item_ids_in_pane =
 9713                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9714            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9715            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9716            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9717            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9718            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9719
 9720            // Single pane left: no-op
 9721            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9722        });
 9723
 9724        workspace.update(cx, |workspace, _cx| {
 9725            let active_pane = workspace.active_pane();
 9726            assert_eq!(top_pane_id, active_pane.entity_id());
 9727        });
 9728    }
 9729
 9730    fn add_an_item_to_active_pane(
 9731        cx: &mut VisualTestContext,
 9732        workspace: &Entity<Workspace>,
 9733        item_id: u64,
 9734    ) -> Entity<TestItem> {
 9735        let item = cx.new(|cx| {
 9736            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9737                item_id,
 9738                "item{item_id}.txt",
 9739                cx,
 9740            )])
 9741        });
 9742        workspace.update_in(cx, |workspace, window, cx| {
 9743            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9744        });
 9745        item
 9746    }
 9747
 9748    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9749        workspace.update_in(cx, |workspace, window, cx| {
 9750            workspace.split_pane(
 9751                workspace.active_pane().clone(),
 9752                SplitDirection::Right,
 9753                window,
 9754                cx,
 9755            )
 9756        })
 9757    }
 9758
 9759    #[gpui::test]
 9760    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9761        init_test(cx);
 9762        let fs = FakeFs::new(cx.executor());
 9763        let project = Project::test(fs, None, cx).await;
 9764        let (workspace, cx) =
 9765            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9766
 9767        add_an_item_to_active_pane(cx, &workspace, 1);
 9768        split_pane(cx, &workspace);
 9769        add_an_item_to_active_pane(cx, &workspace, 2);
 9770        split_pane(cx, &workspace); // empty pane
 9771        split_pane(cx, &workspace);
 9772        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9773
 9774        cx.executor().run_until_parked();
 9775
 9776        workspace.update(cx, |workspace, cx| {
 9777            let num_panes = workspace.panes().len();
 9778            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9779            let active_item = workspace
 9780                .active_pane()
 9781                .read(cx)
 9782                .active_item()
 9783                .expect("item is in focus");
 9784
 9785            assert_eq!(num_panes, 4);
 9786            assert_eq!(num_items_in_current_pane, 1);
 9787            assert_eq!(active_item.item_id(), last_item.item_id());
 9788        });
 9789
 9790        workspace.update_in(cx, |workspace, window, cx| {
 9791            workspace.join_all_panes(window, cx);
 9792        });
 9793
 9794        workspace.update(cx, |workspace, cx| {
 9795            let num_panes = workspace.panes().len();
 9796            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9797            let active_item = workspace
 9798                .active_pane()
 9799                .read(cx)
 9800                .active_item()
 9801                .expect("item is in focus");
 9802
 9803            assert_eq!(num_panes, 1);
 9804            assert_eq!(num_items_in_current_pane, 3);
 9805            assert_eq!(active_item.item_id(), last_item.item_id());
 9806        });
 9807    }
 9808    struct TestModal(FocusHandle);
 9809
 9810    impl TestModal {
 9811        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9812            Self(cx.focus_handle())
 9813        }
 9814    }
 9815
 9816    impl EventEmitter<DismissEvent> for TestModal {}
 9817
 9818    impl Focusable for TestModal {
 9819        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9820            self.0.clone()
 9821        }
 9822    }
 9823
 9824    impl ModalView for TestModal {}
 9825
 9826    impl Render for TestModal {
 9827        fn render(
 9828            &mut self,
 9829            _window: &mut Window,
 9830            _cx: &mut Context<TestModal>,
 9831        ) -> impl IntoElement {
 9832            div().track_focus(&self.0)
 9833        }
 9834    }
 9835
 9836    #[gpui::test]
 9837    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9838        init_test(cx);
 9839        let fs = FakeFs::new(cx.executor());
 9840
 9841        let project = Project::test(fs, [], cx).await;
 9842        let (workspace, cx) =
 9843            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9844
 9845        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9846            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9847            workspace.add_panel(panel_1.clone(), window, cx);
 9848            workspace.toggle_dock(DockPosition::Left, window, cx);
 9849            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9850            workspace.add_panel(panel_2.clone(), window, cx);
 9851            workspace.toggle_dock(DockPosition::Right, window, cx);
 9852
 9853            let left_dock = workspace.left_dock();
 9854            assert_eq!(
 9855                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9856                panel_1.panel_id()
 9857            );
 9858            assert_eq!(
 9859                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9860                panel_1.size(window, cx)
 9861            );
 9862
 9863            left_dock.update(cx, |left_dock, cx| {
 9864                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9865            });
 9866            assert_eq!(
 9867                workspace
 9868                    .right_dock()
 9869                    .read(cx)
 9870                    .visible_panel()
 9871                    .unwrap()
 9872                    .panel_id(),
 9873                panel_2.panel_id(),
 9874            );
 9875
 9876            (panel_1, panel_2)
 9877        });
 9878
 9879        // Move panel_1 to the right
 9880        panel_1.update_in(cx, |panel_1, window, cx| {
 9881            panel_1.set_position(DockPosition::Right, window, cx)
 9882        });
 9883
 9884        workspace.update_in(cx, |workspace, window, cx| {
 9885            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9886            // Since it was the only panel on the left, the left dock should now be closed.
 9887            assert!(!workspace.left_dock().read(cx).is_open());
 9888            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9889            let right_dock = workspace.right_dock();
 9890            assert_eq!(
 9891                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9892                panel_1.panel_id()
 9893            );
 9894            assert_eq!(
 9895                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9896                px(1337.)
 9897            );
 9898
 9899            // Now we move panel_2 to the left
 9900            panel_2.set_position(DockPosition::Left, window, cx);
 9901        });
 9902
 9903        workspace.update(cx, |workspace, cx| {
 9904            // Since panel_2 was not visible on the right, we don't open the left dock.
 9905            assert!(!workspace.left_dock().read(cx).is_open());
 9906            // And the right dock is unaffected in its displaying of panel_1
 9907            assert!(workspace.right_dock().read(cx).is_open());
 9908            assert_eq!(
 9909                workspace
 9910                    .right_dock()
 9911                    .read(cx)
 9912                    .visible_panel()
 9913                    .unwrap()
 9914                    .panel_id(),
 9915                panel_1.panel_id(),
 9916            );
 9917        });
 9918
 9919        // Move panel_1 back to the left
 9920        panel_1.update_in(cx, |panel_1, window, cx| {
 9921            panel_1.set_position(DockPosition::Left, window, cx)
 9922        });
 9923
 9924        workspace.update_in(cx, |workspace, window, cx| {
 9925            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9926            let left_dock = workspace.left_dock();
 9927            assert!(left_dock.read(cx).is_open());
 9928            assert_eq!(
 9929                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9930                panel_1.panel_id()
 9931            );
 9932            assert_eq!(
 9933                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9934                px(1337.)
 9935            );
 9936            // And the right dock should be closed as it no longer has any panels.
 9937            assert!(!workspace.right_dock().read(cx).is_open());
 9938
 9939            // Now we move panel_1 to the bottom
 9940            panel_1.set_position(DockPosition::Bottom, window, cx);
 9941        });
 9942
 9943        workspace.update_in(cx, |workspace, window, cx| {
 9944            // Since panel_1 was visible on the left, we close the left dock.
 9945            assert!(!workspace.left_dock().read(cx).is_open());
 9946            // The bottom dock is sized based on the panel's default size,
 9947            // since the panel orientation changed from vertical to horizontal.
 9948            let bottom_dock = workspace.bottom_dock();
 9949            assert_eq!(
 9950                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9951                panel_1.size(window, cx),
 9952            );
 9953            // Close bottom dock and move panel_1 back to the left.
 9954            bottom_dock.update(cx, |bottom_dock, cx| {
 9955                bottom_dock.set_open(false, window, cx)
 9956            });
 9957            panel_1.set_position(DockPosition::Left, window, cx);
 9958        });
 9959
 9960        // Emit activated event on panel 1
 9961        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9962
 9963        // Now the left dock is open and panel_1 is active and focused.
 9964        workspace.update_in(cx, |workspace, window, cx| {
 9965            let left_dock = workspace.left_dock();
 9966            assert!(left_dock.read(cx).is_open());
 9967            assert_eq!(
 9968                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9969                panel_1.panel_id(),
 9970            );
 9971            assert!(panel_1.focus_handle(cx).is_focused(window));
 9972        });
 9973
 9974        // Emit closed event on panel 2, which is not active
 9975        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9976
 9977        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9978        workspace.update(cx, |workspace, cx| {
 9979            let left_dock = workspace.left_dock();
 9980            assert!(left_dock.read(cx).is_open());
 9981            assert_eq!(
 9982                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9983                panel_1.panel_id(),
 9984            );
 9985        });
 9986
 9987        // Emitting a ZoomIn event shows the panel as zoomed.
 9988        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9989        workspace.read_with(cx, |workspace, _| {
 9990            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9991            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9992        });
 9993
 9994        // Move panel to another dock while it is zoomed
 9995        panel_1.update_in(cx, |panel, window, cx| {
 9996            panel.set_position(DockPosition::Right, window, cx)
 9997        });
 9998        workspace.read_with(cx, |workspace, _| {
 9999            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10000
10001            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10002        });
10003
10004        // This is a helper for getting a:
10005        // - valid focus on an element,
10006        // - that isn't a part of the panes and panels system of the Workspace,
10007        // - and doesn't trigger the 'on_focus_lost' API.
10008        let focus_other_view = {
10009            let workspace = workspace.clone();
10010            move |cx: &mut VisualTestContext| {
10011                workspace.update_in(cx, |workspace, window, cx| {
10012                    if workspace.active_modal::<TestModal>(cx).is_some() {
10013                        workspace.toggle_modal(window, cx, TestModal::new);
10014                        workspace.toggle_modal(window, cx, TestModal::new);
10015                    } else {
10016                        workspace.toggle_modal(window, cx, TestModal::new);
10017                    }
10018                })
10019            }
10020        };
10021
10022        // If focus is transferred to another view that's not a panel or another pane, we still show
10023        // the panel as zoomed.
10024        focus_other_view(cx);
10025        workspace.read_with(cx, |workspace, _| {
10026            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10027            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10028        });
10029
10030        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10031        workspace.update_in(cx, |_workspace, window, cx| {
10032            cx.focus_self(window);
10033        });
10034        workspace.read_with(cx, |workspace, _| {
10035            assert_eq!(workspace.zoomed, None);
10036            assert_eq!(workspace.zoomed_position, None);
10037        });
10038
10039        // If focus is transferred again to another view that's not a panel or a pane, we won't
10040        // show the panel as zoomed because it wasn't zoomed before.
10041        focus_other_view(cx);
10042        workspace.read_with(cx, |workspace, _| {
10043            assert_eq!(workspace.zoomed, None);
10044            assert_eq!(workspace.zoomed_position, None);
10045        });
10046
10047        // When the panel is activated, it is zoomed again.
10048        cx.dispatch_action(ToggleRightDock);
10049        workspace.read_with(cx, |workspace, _| {
10050            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10051            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10052        });
10053
10054        // Emitting a ZoomOut event unzooms the panel.
10055        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10056        workspace.read_with(cx, |workspace, _| {
10057            assert_eq!(workspace.zoomed, None);
10058            assert_eq!(workspace.zoomed_position, None);
10059        });
10060
10061        // Emit closed event on panel 1, which is active
10062        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10063
10064        // Now the left dock is closed, because panel_1 was the active panel
10065        workspace.update(cx, |workspace, cx| {
10066            let right_dock = workspace.right_dock();
10067            assert!(!right_dock.read(cx).is_open());
10068        });
10069    }
10070
10071    #[gpui::test]
10072    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10073        init_test(cx);
10074
10075        let fs = FakeFs::new(cx.background_executor.clone());
10076        let project = Project::test(fs, [], cx).await;
10077        let (workspace, cx) =
10078            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10079        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10080
10081        let dirty_regular_buffer = cx.new(|cx| {
10082            TestItem::new(cx)
10083                .with_dirty(true)
10084                .with_label("1.txt")
10085                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10086        });
10087        let dirty_regular_buffer_2 = cx.new(|cx| {
10088            TestItem::new(cx)
10089                .with_dirty(true)
10090                .with_label("2.txt")
10091                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10092        });
10093        let dirty_multi_buffer_with_both = cx.new(|cx| {
10094            TestItem::new(cx)
10095                .with_dirty(true)
10096                .with_buffer_kind(ItemBufferKind::Multibuffer)
10097                .with_label("Fake Project Search")
10098                .with_project_items(&[
10099                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10100                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10101                ])
10102        });
10103        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10104        workspace.update_in(cx, |workspace, window, cx| {
10105            workspace.add_item(
10106                pane.clone(),
10107                Box::new(dirty_regular_buffer.clone()),
10108                None,
10109                false,
10110                false,
10111                window,
10112                cx,
10113            );
10114            workspace.add_item(
10115                pane.clone(),
10116                Box::new(dirty_regular_buffer_2.clone()),
10117                None,
10118                false,
10119                false,
10120                window,
10121                cx,
10122            );
10123            workspace.add_item(
10124                pane.clone(),
10125                Box::new(dirty_multi_buffer_with_both.clone()),
10126                None,
10127                false,
10128                false,
10129                window,
10130                cx,
10131            );
10132        });
10133
10134        pane.update_in(cx, |pane, window, cx| {
10135            pane.activate_item(2, true, true, window, cx);
10136            assert_eq!(
10137                pane.active_item().unwrap().item_id(),
10138                multi_buffer_with_both_files_id,
10139                "Should select the multi buffer in the pane"
10140            );
10141        });
10142        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10143            pane.close_other_items(
10144                &CloseOtherItems {
10145                    save_intent: Some(SaveIntent::Save),
10146                    close_pinned: true,
10147                },
10148                None,
10149                window,
10150                cx,
10151            )
10152        });
10153        cx.background_executor.run_until_parked();
10154        assert!(!cx.has_pending_prompt());
10155        close_all_but_multi_buffer_task
10156            .await
10157            .expect("Closing all buffers but the multi buffer failed");
10158        pane.update(cx, |pane, cx| {
10159            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10160            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10161            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10162            assert_eq!(pane.items_len(), 1);
10163            assert_eq!(
10164                pane.active_item().unwrap().item_id(),
10165                multi_buffer_with_both_files_id,
10166                "Should have only the multi buffer left in the pane"
10167            );
10168            assert!(
10169                dirty_multi_buffer_with_both.read(cx).is_dirty,
10170                "The multi buffer containing the unsaved buffer should still be dirty"
10171            );
10172        });
10173
10174        dirty_regular_buffer.update(cx, |buffer, cx| {
10175            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10176        });
10177
10178        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10179            pane.close_active_item(
10180                &CloseActiveItem {
10181                    save_intent: Some(SaveIntent::Close),
10182                    close_pinned: false,
10183                },
10184                window,
10185                cx,
10186            )
10187        });
10188        cx.background_executor.run_until_parked();
10189        assert!(
10190            cx.has_pending_prompt(),
10191            "Dirty multi buffer should prompt a save dialog"
10192        );
10193        cx.simulate_prompt_answer("Save");
10194        cx.background_executor.run_until_parked();
10195        close_multi_buffer_task
10196            .await
10197            .expect("Closing the multi buffer failed");
10198        pane.update(cx, |pane, cx| {
10199            assert_eq!(
10200                dirty_multi_buffer_with_both.read(cx).save_count,
10201                1,
10202                "Multi buffer item should get be saved"
10203            );
10204            // Test impl does not save inner items, so we do not assert them
10205            assert_eq!(
10206                pane.items_len(),
10207                0,
10208                "No more items should be left in the pane"
10209            );
10210            assert!(pane.active_item().is_none());
10211        });
10212    }
10213
10214    #[gpui::test]
10215    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10216        cx: &mut TestAppContext,
10217    ) {
10218        init_test(cx);
10219
10220        let fs = FakeFs::new(cx.background_executor.clone());
10221        let project = Project::test(fs, [], cx).await;
10222        let (workspace, cx) =
10223            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10224        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10225
10226        let dirty_regular_buffer = cx.new(|cx| {
10227            TestItem::new(cx)
10228                .with_dirty(true)
10229                .with_label("1.txt")
10230                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10231        });
10232        let dirty_regular_buffer_2 = cx.new(|cx| {
10233            TestItem::new(cx)
10234                .with_dirty(true)
10235                .with_label("2.txt")
10236                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10237        });
10238        let clear_regular_buffer = cx.new(|cx| {
10239            TestItem::new(cx)
10240                .with_label("3.txt")
10241                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10242        });
10243
10244        let dirty_multi_buffer_with_both = cx.new(|cx| {
10245            TestItem::new(cx)
10246                .with_dirty(true)
10247                .with_buffer_kind(ItemBufferKind::Multibuffer)
10248                .with_label("Fake Project Search")
10249                .with_project_items(&[
10250                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10251                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10252                    clear_regular_buffer.read(cx).project_items[0].clone(),
10253                ])
10254        });
10255        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10256        workspace.update_in(cx, |workspace, window, cx| {
10257            workspace.add_item(
10258                pane.clone(),
10259                Box::new(dirty_regular_buffer.clone()),
10260                None,
10261                false,
10262                false,
10263                window,
10264                cx,
10265            );
10266            workspace.add_item(
10267                pane.clone(),
10268                Box::new(dirty_multi_buffer_with_both.clone()),
10269                None,
10270                false,
10271                false,
10272                window,
10273                cx,
10274            );
10275        });
10276
10277        pane.update_in(cx, |pane, window, cx| {
10278            pane.activate_item(1, true, true, window, cx);
10279            assert_eq!(
10280                pane.active_item().unwrap().item_id(),
10281                multi_buffer_with_both_files_id,
10282                "Should select the multi buffer in the pane"
10283            );
10284        });
10285        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10286            pane.close_active_item(
10287                &CloseActiveItem {
10288                    save_intent: None,
10289                    close_pinned: false,
10290                },
10291                window,
10292                cx,
10293            )
10294        });
10295        cx.background_executor.run_until_parked();
10296        assert!(
10297            cx.has_pending_prompt(),
10298            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10299        );
10300    }
10301
10302    /// Tests that when `close_on_file_delete` is enabled, files are automatically
10303    /// closed when they are deleted from disk.
10304    #[gpui::test]
10305    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10306        init_test(cx);
10307
10308        // Enable the close_on_disk_deletion setting
10309        cx.update_global(|store: &mut SettingsStore, cx| {
10310            store.update_user_settings(cx, |settings| {
10311                settings.workspace.close_on_file_delete = Some(true);
10312            });
10313        });
10314
10315        let fs = FakeFs::new(cx.background_executor.clone());
10316        let project = Project::test(fs, [], cx).await;
10317        let (workspace, cx) =
10318            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10319        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10320
10321        // Create a test item that simulates a file
10322        let item = cx.new(|cx| {
10323            TestItem::new(cx)
10324                .with_label("test.txt")
10325                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10326        });
10327
10328        // Add item to workspace
10329        workspace.update_in(cx, |workspace, window, cx| {
10330            workspace.add_item(
10331                pane.clone(),
10332                Box::new(item.clone()),
10333                None,
10334                false,
10335                false,
10336                window,
10337                cx,
10338            );
10339        });
10340
10341        // Verify the item is in the pane
10342        pane.read_with(cx, |pane, _| {
10343            assert_eq!(pane.items().count(), 1);
10344        });
10345
10346        // Simulate file deletion by setting the item's deleted state
10347        item.update(cx, |item, _| {
10348            item.set_has_deleted_file(true);
10349        });
10350
10351        // Emit UpdateTab event to trigger the close behavior
10352        cx.run_until_parked();
10353        item.update(cx, |_, cx| {
10354            cx.emit(ItemEvent::UpdateTab);
10355        });
10356
10357        // Allow the close operation to complete
10358        cx.run_until_parked();
10359
10360        // Verify the item was automatically closed
10361        pane.read_with(cx, |pane, _| {
10362            assert_eq!(
10363                pane.items().count(),
10364                0,
10365                "Item should be automatically closed when file is deleted"
10366            );
10367        });
10368    }
10369
10370    /// Tests that when `close_on_file_delete` is disabled (default), files remain
10371    /// open with a strikethrough when they are deleted from disk.
10372    #[gpui::test]
10373    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10374        init_test(cx);
10375
10376        // Ensure close_on_disk_deletion is disabled (default)
10377        cx.update_global(|store: &mut SettingsStore, cx| {
10378            store.update_user_settings(cx, |settings| {
10379                settings.workspace.close_on_file_delete = Some(false);
10380            });
10381        });
10382
10383        let fs = FakeFs::new(cx.background_executor.clone());
10384        let project = Project::test(fs, [], cx).await;
10385        let (workspace, cx) =
10386            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10387        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10388
10389        // Create a test item that simulates a file
10390        let item = cx.new(|cx| {
10391            TestItem::new(cx)
10392                .with_label("test.txt")
10393                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10394        });
10395
10396        // Add item to workspace
10397        workspace.update_in(cx, |workspace, window, cx| {
10398            workspace.add_item(
10399                pane.clone(),
10400                Box::new(item.clone()),
10401                None,
10402                false,
10403                false,
10404                window,
10405                cx,
10406            );
10407        });
10408
10409        // Verify the item is in the pane
10410        pane.read_with(cx, |pane, _| {
10411            assert_eq!(pane.items().count(), 1);
10412        });
10413
10414        // Simulate file deletion
10415        item.update(cx, |item, _| {
10416            item.set_has_deleted_file(true);
10417        });
10418
10419        // Emit UpdateTab event
10420        cx.run_until_parked();
10421        item.update(cx, |_, cx| {
10422            cx.emit(ItemEvent::UpdateTab);
10423        });
10424
10425        // Allow any potential close operation to complete
10426        cx.run_until_parked();
10427
10428        // Verify the item remains open (with strikethrough)
10429        pane.read_with(cx, |pane, _| {
10430            assert_eq!(
10431                pane.items().count(),
10432                1,
10433                "Item should remain open when close_on_disk_deletion is disabled"
10434            );
10435        });
10436
10437        // Verify the item shows as deleted
10438        item.read_with(cx, |item, _| {
10439            assert!(
10440                item.has_deleted_file,
10441                "Item should be marked as having deleted file"
10442            );
10443        });
10444    }
10445
10446    /// Tests that dirty files are not automatically closed when deleted from disk,
10447    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10448    /// unsaved changes without being prompted.
10449    #[gpui::test]
10450    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10451        init_test(cx);
10452
10453        // Enable the close_on_file_delete setting
10454        cx.update_global(|store: &mut SettingsStore, cx| {
10455            store.update_user_settings(cx, |settings| {
10456                settings.workspace.close_on_file_delete = Some(true);
10457            });
10458        });
10459
10460        let fs = FakeFs::new(cx.background_executor.clone());
10461        let project = Project::test(fs, [], cx).await;
10462        let (workspace, cx) =
10463            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10464        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10465
10466        // Create a dirty test item
10467        let item = cx.new(|cx| {
10468            TestItem::new(cx)
10469                .with_dirty(true)
10470                .with_label("test.txt")
10471                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10472        });
10473
10474        // Add item to workspace
10475        workspace.update_in(cx, |workspace, window, cx| {
10476            workspace.add_item(
10477                pane.clone(),
10478                Box::new(item.clone()),
10479                None,
10480                false,
10481                false,
10482                window,
10483                cx,
10484            );
10485        });
10486
10487        // Simulate file deletion
10488        item.update(cx, |item, _| {
10489            item.set_has_deleted_file(true);
10490        });
10491
10492        // Emit UpdateTab event to trigger the close behavior
10493        cx.run_until_parked();
10494        item.update(cx, |_, cx| {
10495            cx.emit(ItemEvent::UpdateTab);
10496        });
10497
10498        // Allow any potential close operation to complete
10499        cx.run_until_parked();
10500
10501        // Verify the item remains open (dirty files are not auto-closed)
10502        pane.read_with(cx, |pane, _| {
10503            assert_eq!(
10504                pane.items().count(),
10505                1,
10506                "Dirty items should not be automatically closed even when file is deleted"
10507            );
10508        });
10509
10510        // Verify the item is marked as deleted and still dirty
10511        item.read_with(cx, |item, _| {
10512            assert!(
10513                item.has_deleted_file,
10514                "Item should be marked as having deleted file"
10515            );
10516            assert!(item.is_dirty, "Item should still be dirty");
10517        });
10518    }
10519
10520    /// Tests that navigation history is cleaned up when files are auto-closed
10521    /// due to deletion from disk.
10522    #[gpui::test]
10523    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10524        init_test(cx);
10525
10526        // Enable the close_on_file_delete setting
10527        cx.update_global(|store: &mut SettingsStore, cx| {
10528            store.update_user_settings(cx, |settings| {
10529                settings.workspace.close_on_file_delete = Some(true);
10530            });
10531        });
10532
10533        let fs = FakeFs::new(cx.background_executor.clone());
10534        let project = Project::test(fs, [], cx).await;
10535        let (workspace, cx) =
10536            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10537        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10538
10539        // Create test items
10540        let item1 = cx.new(|cx| {
10541            TestItem::new(cx)
10542                .with_label("test1.txt")
10543                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10544        });
10545        let item1_id = item1.item_id();
10546
10547        let item2 = cx.new(|cx| {
10548            TestItem::new(cx)
10549                .with_label("test2.txt")
10550                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10551        });
10552
10553        // Add items to workspace
10554        workspace.update_in(cx, |workspace, window, cx| {
10555            workspace.add_item(
10556                pane.clone(),
10557                Box::new(item1.clone()),
10558                None,
10559                false,
10560                false,
10561                window,
10562                cx,
10563            );
10564            workspace.add_item(
10565                pane.clone(),
10566                Box::new(item2.clone()),
10567                None,
10568                false,
10569                false,
10570                window,
10571                cx,
10572            );
10573        });
10574
10575        // Activate item1 to ensure it gets navigation entries
10576        pane.update_in(cx, |pane, window, cx| {
10577            pane.activate_item(0, true, true, window, cx);
10578        });
10579
10580        // Switch to item2 and back to create navigation history
10581        pane.update_in(cx, |pane, window, cx| {
10582            pane.activate_item(1, true, true, window, cx);
10583        });
10584        cx.run_until_parked();
10585
10586        pane.update_in(cx, |pane, window, cx| {
10587            pane.activate_item(0, true, true, window, cx);
10588        });
10589        cx.run_until_parked();
10590
10591        // Simulate file deletion for item1
10592        item1.update(cx, |item, _| {
10593            item.set_has_deleted_file(true);
10594        });
10595
10596        // Emit UpdateTab event to trigger the close behavior
10597        item1.update(cx, |_, cx| {
10598            cx.emit(ItemEvent::UpdateTab);
10599        });
10600        cx.run_until_parked();
10601
10602        // Verify item1 was closed
10603        pane.read_with(cx, |pane, _| {
10604            assert_eq!(
10605                pane.items().count(),
10606                1,
10607                "Should have 1 item remaining after auto-close"
10608            );
10609        });
10610
10611        // Check navigation history after close
10612        let has_item = pane.read_with(cx, |pane, cx| {
10613            let mut has_item = false;
10614            pane.nav_history().for_each_entry(cx, |entry, _| {
10615                if entry.item.id() == item1_id {
10616                    has_item = true;
10617                }
10618            });
10619            has_item
10620        });
10621
10622        assert!(
10623            !has_item,
10624            "Navigation history should not contain closed item entries"
10625        );
10626    }
10627
10628    #[gpui::test]
10629    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10630        cx: &mut TestAppContext,
10631    ) {
10632        init_test(cx);
10633
10634        let fs = FakeFs::new(cx.background_executor.clone());
10635        let project = Project::test(fs, [], cx).await;
10636        let (workspace, cx) =
10637            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10638        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10639
10640        let dirty_regular_buffer = cx.new(|cx| {
10641            TestItem::new(cx)
10642                .with_dirty(true)
10643                .with_label("1.txt")
10644                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10645        });
10646        let dirty_regular_buffer_2 = cx.new(|cx| {
10647            TestItem::new(cx)
10648                .with_dirty(true)
10649                .with_label("2.txt")
10650                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10651        });
10652        let clear_regular_buffer = cx.new(|cx| {
10653            TestItem::new(cx)
10654                .with_label("3.txt")
10655                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10656        });
10657
10658        let dirty_multi_buffer = cx.new(|cx| {
10659            TestItem::new(cx)
10660                .with_dirty(true)
10661                .with_buffer_kind(ItemBufferKind::Multibuffer)
10662                .with_label("Fake Project Search")
10663                .with_project_items(&[
10664                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10665                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10666                    clear_regular_buffer.read(cx).project_items[0].clone(),
10667                ])
10668        });
10669        workspace.update_in(cx, |workspace, window, cx| {
10670            workspace.add_item(
10671                pane.clone(),
10672                Box::new(dirty_regular_buffer.clone()),
10673                None,
10674                false,
10675                false,
10676                window,
10677                cx,
10678            );
10679            workspace.add_item(
10680                pane.clone(),
10681                Box::new(dirty_regular_buffer_2.clone()),
10682                None,
10683                false,
10684                false,
10685                window,
10686                cx,
10687            );
10688            workspace.add_item(
10689                pane.clone(),
10690                Box::new(dirty_multi_buffer.clone()),
10691                None,
10692                false,
10693                false,
10694                window,
10695                cx,
10696            );
10697        });
10698
10699        pane.update_in(cx, |pane, window, cx| {
10700            pane.activate_item(2, true, true, window, cx);
10701            assert_eq!(
10702                pane.active_item().unwrap().item_id(),
10703                dirty_multi_buffer.item_id(),
10704                "Should select the multi buffer in the pane"
10705            );
10706        });
10707        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10708            pane.close_active_item(
10709                &CloseActiveItem {
10710                    save_intent: None,
10711                    close_pinned: false,
10712                },
10713                window,
10714                cx,
10715            )
10716        });
10717        cx.background_executor.run_until_parked();
10718        assert!(
10719            !cx.has_pending_prompt(),
10720            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10721        );
10722        close_multi_buffer_task
10723            .await
10724            .expect("Closing multi buffer failed");
10725        pane.update(cx, |pane, cx| {
10726            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10727            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10728            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10729            assert_eq!(
10730                pane.items()
10731                    .map(|item| item.item_id())
10732                    .sorted()
10733                    .collect::<Vec<_>>(),
10734                vec![
10735                    dirty_regular_buffer.item_id(),
10736                    dirty_regular_buffer_2.item_id(),
10737                ],
10738                "Should have no multi buffer left in the pane"
10739            );
10740            assert!(dirty_regular_buffer.read(cx).is_dirty);
10741            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10742        });
10743    }
10744
10745    #[gpui::test]
10746    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10747        init_test(cx);
10748        let fs = FakeFs::new(cx.executor());
10749        let project = Project::test(fs, [], cx).await;
10750        let (workspace, cx) =
10751            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10752
10753        // Add a new panel to the right dock, opening the dock and setting the
10754        // focus to the new panel.
10755        let panel = workspace.update_in(cx, |workspace, window, cx| {
10756            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10757            workspace.add_panel(panel.clone(), window, cx);
10758
10759            workspace
10760                .right_dock()
10761                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10762
10763            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10764
10765            panel
10766        });
10767
10768        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10769        // panel to the next valid position which, in this case, is the left
10770        // dock.
10771        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10772        workspace.update(cx, |workspace, cx| {
10773            assert!(workspace.left_dock().read(cx).is_open());
10774            assert_eq!(panel.read(cx).position, DockPosition::Left);
10775        });
10776
10777        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10778        // panel to the next valid position which, in this case, is the bottom
10779        // dock.
10780        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10781        workspace.update(cx, |workspace, cx| {
10782            assert!(workspace.bottom_dock().read(cx).is_open());
10783            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10784        });
10785
10786        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10787        // around moving the panel to its initial position, the right dock.
10788        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10789        workspace.update(cx, |workspace, cx| {
10790            assert!(workspace.right_dock().read(cx).is_open());
10791            assert_eq!(panel.read(cx).position, DockPosition::Right);
10792        });
10793
10794        // Remove focus from the panel, ensuring that, if the panel is not
10795        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10796        // the panel's position, so the panel is still in the right dock.
10797        workspace.update_in(cx, |workspace, window, cx| {
10798            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10799        });
10800
10801        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10802        workspace.update(cx, |workspace, cx| {
10803            assert!(workspace.right_dock().read(cx).is_open());
10804            assert_eq!(panel.read(cx).position, DockPosition::Right);
10805        });
10806    }
10807
10808    #[gpui::test]
10809    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10810        init_test(cx);
10811
10812        let fs = FakeFs::new(cx.executor());
10813        let project = Project::test(fs, [], cx).await;
10814        let (workspace, cx) =
10815            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10816
10817        let item_1 = cx.new(|cx| {
10818            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10819        });
10820        workspace.update_in(cx, |workspace, window, cx| {
10821            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10822            workspace.move_item_to_pane_in_direction(
10823                &MoveItemToPaneInDirection {
10824                    direction: SplitDirection::Right,
10825                    focus: true,
10826                    clone: false,
10827                },
10828                window,
10829                cx,
10830            );
10831            workspace.move_item_to_pane_at_index(
10832                &MoveItemToPane {
10833                    destination: 3,
10834                    focus: true,
10835                    clone: false,
10836                },
10837                window,
10838                cx,
10839            );
10840
10841            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10842            assert_eq!(
10843                pane_items_paths(&workspace.active_pane, cx),
10844                vec!["first.txt".to_string()],
10845                "Single item was not moved anywhere"
10846            );
10847        });
10848
10849        let item_2 = cx.new(|cx| {
10850            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10851        });
10852        workspace.update_in(cx, |workspace, window, cx| {
10853            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10854            assert_eq!(
10855                pane_items_paths(&workspace.panes[0], cx),
10856                vec!["first.txt".to_string(), "second.txt".to_string()],
10857            );
10858            workspace.move_item_to_pane_in_direction(
10859                &MoveItemToPaneInDirection {
10860                    direction: SplitDirection::Right,
10861                    focus: true,
10862                    clone: false,
10863                },
10864                window,
10865                cx,
10866            );
10867
10868            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10869            assert_eq!(
10870                pane_items_paths(&workspace.panes[0], cx),
10871                vec!["first.txt".to_string()],
10872                "After moving, one item should be left in the original pane"
10873            );
10874            assert_eq!(
10875                pane_items_paths(&workspace.panes[1], cx),
10876                vec!["second.txt".to_string()],
10877                "New item should have been moved to the new pane"
10878            );
10879        });
10880
10881        let item_3 = cx.new(|cx| {
10882            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10883        });
10884        workspace.update_in(cx, |workspace, window, cx| {
10885            let original_pane = workspace.panes[0].clone();
10886            workspace.set_active_pane(&original_pane, window, cx);
10887            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10888            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10889            assert_eq!(
10890                pane_items_paths(&workspace.active_pane, cx),
10891                vec!["first.txt".to_string(), "third.txt".to_string()],
10892                "New pane should be ready to move one item out"
10893            );
10894
10895            workspace.move_item_to_pane_at_index(
10896                &MoveItemToPane {
10897                    destination: 3,
10898                    focus: true,
10899                    clone: false,
10900                },
10901                window,
10902                cx,
10903            );
10904            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10905            assert_eq!(
10906                pane_items_paths(&workspace.active_pane, cx),
10907                vec!["first.txt".to_string()],
10908                "After moving, one item should be left in the original pane"
10909            );
10910            assert_eq!(
10911                pane_items_paths(&workspace.panes[1], cx),
10912                vec!["second.txt".to_string()],
10913                "Previously created pane should be unchanged"
10914            );
10915            assert_eq!(
10916                pane_items_paths(&workspace.panes[2], cx),
10917                vec!["third.txt".to_string()],
10918                "New item should have been moved to the new pane"
10919            );
10920        });
10921    }
10922
10923    #[gpui::test]
10924    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10925        init_test(cx);
10926
10927        let fs = FakeFs::new(cx.executor());
10928        let project = Project::test(fs, [], cx).await;
10929        let (workspace, cx) =
10930            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10931
10932        let item_1 = cx.new(|cx| {
10933            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10934        });
10935        workspace.update_in(cx, |workspace, window, cx| {
10936            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10937            workspace.move_item_to_pane_in_direction(
10938                &MoveItemToPaneInDirection {
10939                    direction: SplitDirection::Right,
10940                    focus: true,
10941                    clone: true,
10942                },
10943                window,
10944                cx,
10945            );
10946            workspace.move_item_to_pane_at_index(
10947                &MoveItemToPane {
10948                    destination: 3,
10949                    focus: true,
10950                    clone: true,
10951                },
10952                window,
10953                cx,
10954            );
10955        });
10956        cx.run_until_parked();
10957
10958        workspace.update(cx, |workspace, cx| {
10959            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10960            for pane in workspace.panes() {
10961                assert_eq!(
10962                    pane_items_paths(pane, cx),
10963                    vec!["first.txt".to_string()],
10964                    "Single item exists in all panes"
10965                );
10966            }
10967        });
10968
10969        // verify that the active pane has been updated after waiting for the
10970        // pane focus event to fire and resolve
10971        workspace.read_with(cx, |workspace, _app| {
10972            assert_eq!(
10973                workspace.active_pane(),
10974                &workspace.panes[2],
10975                "The third pane should be the active one: {:?}",
10976                workspace.panes
10977            );
10978        })
10979    }
10980
10981    mod register_project_item_tests {
10982
10983        use super::*;
10984
10985        // View
10986        struct TestPngItemView {
10987            focus_handle: FocusHandle,
10988        }
10989        // Model
10990        struct TestPngItem {}
10991
10992        impl project::ProjectItem for TestPngItem {
10993            fn try_open(
10994                _project: &Entity<Project>,
10995                path: &ProjectPath,
10996                cx: &mut App,
10997            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10998                if path.path.extension().unwrap() == "png" {
10999                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11000                } else {
11001                    None
11002                }
11003            }
11004
11005            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11006                None
11007            }
11008
11009            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11010                None
11011            }
11012
11013            fn is_dirty(&self) -> bool {
11014                false
11015            }
11016        }
11017
11018        impl Item for TestPngItemView {
11019            type Event = ();
11020            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11021                "".into()
11022            }
11023        }
11024        impl EventEmitter<()> for TestPngItemView {}
11025        impl Focusable for TestPngItemView {
11026            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11027                self.focus_handle.clone()
11028            }
11029        }
11030
11031        impl Render for TestPngItemView {
11032            fn render(
11033                &mut self,
11034                _window: &mut Window,
11035                _cx: &mut Context<Self>,
11036            ) -> impl IntoElement {
11037                Empty
11038            }
11039        }
11040
11041        impl ProjectItem for TestPngItemView {
11042            type Item = TestPngItem;
11043
11044            fn for_project_item(
11045                _project: Entity<Project>,
11046                _pane: Option<&Pane>,
11047                _item: Entity<Self::Item>,
11048                _: &mut Window,
11049                cx: &mut Context<Self>,
11050            ) -> Self
11051            where
11052                Self: Sized,
11053            {
11054                Self {
11055                    focus_handle: cx.focus_handle(),
11056                }
11057            }
11058        }
11059
11060        // View
11061        struct TestIpynbItemView {
11062            focus_handle: FocusHandle,
11063        }
11064        // Model
11065        struct TestIpynbItem {}
11066
11067        impl project::ProjectItem for TestIpynbItem {
11068            fn try_open(
11069                _project: &Entity<Project>,
11070                path: &ProjectPath,
11071                cx: &mut App,
11072            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11073                if path.path.extension().unwrap() == "ipynb" {
11074                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11075                } else {
11076                    None
11077                }
11078            }
11079
11080            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11081                None
11082            }
11083
11084            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11085                None
11086            }
11087
11088            fn is_dirty(&self) -> bool {
11089                false
11090            }
11091        }
11092
11093        impl Item for TestIpynbItemView {
11094            type Event = ();
11095            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11096                "".into()
11097            }
11098        }
11099        impl EventEmitter<()> for TestIpynbItemView {}
11100        impl Focusable for TestIpynbItemView {
11101            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11102                self.focus_handle.clone()
11103            }
11104        }
11105
11106        impl Render for TestIpynbItemView {
11107            fn render(
11108                &mut self,
11109                _window: &mut Window,
11110                _cx: &mut Context<Self>,
11111            ) -> impl IntoElement {
11112                Empty
11113            }
11114        }
11115
11116        impl ProjectItem for TestIpynbItemView {
11117            type Item = TestIpynbItem;
11118
11119            fn for_project_item(
11120                _project: Entity<Project>,
11121                _pane: Option<&Pane>,
11122                _item: Entity<Self::Item>,
11123                _: &mut Window,
11124                cx: &mut Context<Self>,
11125            ) -> Self
11126            where
11127                Self: Sized,
11128            {
11129                Self {
11130                    focus_handle: cx.focus_handle(),
11131                }
11132            }
11133        }
11134
11135        struct TestAlternatePngItemView {
11136            focus_handle: FocusHandle,
11137        }
11138
11139        impl Item for TestAlternatePngItemView {
11140            type Event = ();
11141            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11142                "".into()
11143            }
11144        }
11145
11146        impl EventEmitter<()> for TestAlternatePngItemView {}
11147        impl Focusable for TestAlternatePngItemView {
11148            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11149                self.focus_handle.clone()
11150            }
11151        }
11152
11153        impl Render for TestAlternatePngItemView {
11154            fn render(
11155                &mut self,
11156                _window: &mut Window,
11157                _cx: &mut Context<Self>,
11158            ) -> impl IntoElement {
11159                Empty
11160            }
11161        }
11162
11163        impl ProjectItem for TestAlternatePngItemView {
11164            type Item = TestPngItem;
11165
11166            fn for_project_item(
11167                _project: Entity<Project>,
11168                _pane: Option<&Pane>,
11169                _item: Entity<Self::Item>,
11170                _: &mut Window,
11171                cx: &mut Context<Self>,
11172            ) -> Self
11173            where
11174                Self: Sized,
11175            {
11176                Self {
11177                    focus_handle: cx.focus_handle(),
11178                }
11179            }
11180        }
11181
11182        #[gpui::test]
11183        async fn test_register_project_item(cx: &mut TestAppContext) {
11184            init_test(cx);
11185
11186            cx.update(|cx| {
11187                register_project_item::<TestPngItemView>(cx);
11188                register_project_item::<TestIpynbItemView>(cx);
11189            });
11190
11191            let fs = FakeFs::new(cx.executor());
11192            fs.insert_tree(
11193                "/root1",
11194                json!({
11195                    "one.png": "BINARYDATAHERE",
11196                    "two.ipynb": "{ totally a notebook }",
11197                    "three.txt": "editing text, sure why not?"
11198                }),
11199            )
11200            .await;
11201
11202            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11203            let (workspace, cx) =
11204                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11205
11206            let worktree_id = project.update(cx, |project, cx| {
11207                project.worktrees(cx).next().unwrap().read(cx).id()
11208            });
11209
11210            let handle = workspace
11211                .update_in(cx, |workspace, window, cx| {
11212                    let project_path = (worktree_id, rel_path("one.png"));
11213                    workspace.open_path(project_path, None, true, window, cx)
11214                })
11215                .await
11216                .unwrap();
11217
11218            // Now we can check if the handle we got back errored or not
11219            assert_eq!(
11220                handle.to_any().entity_type(),
11221                TypeId::of::<TestPngItemView>()
11222            );
11223
11224            let handle = workspace
11225                .update_in(cx, |workspace, window, cx| {
11226                    let project_path = (worktree_id, rel_path("two.ipynb"));
11227                    workspace.open_path(project_path, None, true, window, cx)
11228                })
11229                .await
11230                .unwrap();
11231
11232            assert_eq!(
11233                handle.to_any().entity_type(),
11234                TypeId::of::<TestIpynbItemView>()
11235            );
11236
11237            let handle = workspace
11238                .update_in(cx, |workspace, window, cx| {
11239                    let project_path = (worktree_id, rel_path("three.txt"));
11240                    workspace.open_path(project_path, None, true, window, cx)
11241                })
11242                .await;
11243            assert!(handle.is_err());
11244        }
11245
11246        #[gpui::test]
11247        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11248            init_test(cx);
11249
11250            cx.update(|cx| {
11251                register_project_item::<TestPngItemView>(cx);
11252                register_project_item::<TestAlternatePngItemView>(cx);
11253            });
11254
11255            let fs = FakeFs::new(cx.executor());
11256            fs.insert_tree(
11257                "/root1",
11258                json!({
11259                    "one.png": "BINARYDATAHERE",
11260                    "two.ipynb": "{ totally a notebook }",
11261                    "three.txt": "editing text, sure why not?"
11262                }),
11263            )
11264            .await;
11265            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11266            let (workspace, cx) =
11267                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11268            let worktree_id = project.update(cx, |project, cx| {
11269                project.worktrees(cx).next().unwrap().read(cx).id()
11270            });
11271
11272            let handle = workspace
11273                .update_in(cx, |workspace, window, cx| {
11274                    let project_path = (worktree_id, rel_path("one.png"));
11275                    workspace.open_path(project_path, None, true, window, cx)
11276                })
11277                .await
11278                .unwrap();
11279
11280            // This _must_ be the second item registered
11281            assert_eq!(
11282                handle.to_any().entity_type(),
11283                TypeId::of::<TestAlternatePngItemView>()
11284            );
11285
11286            let handle = workspace
11287                .update_in(cx, |workspace, window, cx| {
11288                    let project_path = (worktree_id, rel_path("three.txt"));
11289                    workspace.open_path(project_path, None, true, window, cx)
11290                })
11291                .await;
11292            assert!(handle.is_err());
11293        }
11294    }
11295
11296    #[gpui::test]
11297    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11298        init_test(cx);
11299
11300        let fs = FakeFs::new(cx.executor());
11301        let project = Project::test(fs, [], cx).await;
11302        let (workspace, _cx) =
11303            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11304
11305        // Test with status bar shown (default)
11306        workspace.read_with(cx, |workspace, cx| {
11307            let visible = workspace.status_bar_visible(cx);
11308            assert!(visible, "Status bar should be visible by default");
11309        });
11310
11311        // Test with status bar hidden
11312        cx.update_global(|store: &mut SettingsStore, cx| {
11313            store.update_user_settings(cx, |settings| {
11314                settings.status_bar.get_or_insert_default().show = Some(false);
11315            });
11316        });
11317
11318        workspace.read_with(cx, |workspace, cx| {
11319            let visible = workspace.status_bar_visible(cx);
11320            assert!(!visible, "Status bar should be hidden when show is false");
11321        });
11322
11323        // Test with status bar shown explicitly
11324        cx.update_global(|store: &mut SettingsStore, cx| {
11325            store.update_user_settings(cx, |settings| {
11326                settings.status_bar.get_or_insert_default().show = Some(true);
11327            });
11328        });
11329
11330        workspace.read_with(cx, |workspace, cx| {
11331            let visible = workspace.status_bar_visible(cx);
11332            assert!(visible, "Status bar should be visible when show is true");
11333        });
11334    }
11335
11336    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11337        pane.read(cx)
11338            .items()
11339            .flat_map(|item| {
11340                item.project_paths(cx)
11341                    .into_iter()
11342                    .map(|path| path.path.display(PathStyle::local()).into_owned())
11343            })
11344            .collect()
11345    }
11346
11347    pub fn init_test(cx: &mut TestAppContext) {
11348        cx.update(|cx| {
11349            let settings_store = SettingsStore::test(cx);
11350            cx.set_global(settings_store);
11351            theme::init(theme::LoadThemes::JustBase, cx);
11352            language::init(cx);
11353            crate::init_settings(cx);
11354            Project::init_settings(cx);
11355        });
11356    }
11357
11358    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11359        let item = TestProjectItem::new(id, path, cx);
11360        item.update(cx, |item, _| {
11361            item.is_dirty = true;
11362        });
11363        item
11364    }
11365}