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