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