workspace.rs

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