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