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