workspace.rs

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