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