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        if self.left_dock.read(cx).is_open() {
 6377            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6378                context.set("left_dock", active_panel.panel_key());
 6379            }
 6380        }
 6381
 6382        if self.right_dock.read(cx).is_open() {
 6383            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6384                context.set("right_dock", active_panel.panel_key());
 6385            }
 6386        }
 6387
 6388        if self.bottom_dock.read(cx).is_open() {
 6389            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6390                context.set("bottom_dock", active_panel.panel_key());
 6391            }
 6392        }
 6393
 6394        let centered_layout = self.centered_layout
 6395            && self.center.panes().len() == 1
 6396            && self.active_item(cx).is_some();
 6397        let render_padding = |size| {
 6398            (size > 0.0).then(|| {
 6399                div()
 6400                    .h_full()
 6401                    .w(relative(size))
 6402                    .bg(cx.theme().colors().editor_background)
 6403                    .border_color(cx.theme().colors().pane_group_border)
 6404            })
 6405        };
 6406        let paddings = if centered_layout {
 6407            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6408            (
 6409                render_padding(Self::adjust_padding(settings.left_padding)),
 6410                render_padding(Self::adjust_padding(settings.right_padding)),
 6411            )
 6412        } else {
 6413            (None, None)
 6414        };
 6415        let ui_font = theme::setup_ui_font(window, cx);
 6416
 6417        let theme = cx.theme().clone();
 6418        let colors = theme.colors();
 6419        let notification_entities = self
 6420            .notifications
 6421            .iter()
 6422            .map(|(_, notification)| notification.entity_id())
 6423            .collect::<Vec<_>>();
 6424        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6425
 6426        client_side_decorations(
 6427            self.actions(div(), window, cx)
 6428                .key_context(context)
 6429                .relative()
 6430                .size_full()
 6431                .flex()
 6432                .flex_col()
 6433                .font(ui_font)
 6434                .gap_0()
 6435                .justify_start()
 6436                .items_start()
 6437                .text_color(colors.text)
 6438                .overflow_hidden()
 6439                .children(self.titlebar_item.clone())
 6440                .on_modifiers_changed(move |_, _, cx| {
 6441                    for &id in &notification_entities {
 6442                        cx.notify(id);
 6443                    }
 6444                })
 6445                .child(
 6446                    div()
 6447                        .size_full()
 6448                        .relative()
 6449                        .flex_1()
 6450                        .flex()
 6451                        .flex_col()
 6452                        .child(
 6453                            div()
 6454                                .id("workspace")
 6455                                .bg(colors.background)
 6456                                .relative()
 6457                                .flex_1()
 6458                                .w_full()
 6459                                .flex()
 6460                                .flex_col()
 6461                                .overflow_hidden()
 6462                                .border_t_1()
 6463                                .border_b_1()
 6464                                .border_color(colors.border)
 6465                                .child({
 6466                                    let this = cx.entity();
 6467                                    canvas(
 6468                                        move |bounds, window, cx| {
 6469                                            this.update(cx, |this, cx| {
 6470                                                let bounds_changed = this.bounds != bounds;
 6471                                                this.bounds = bounds;
 6472
 6473                                                if bounds_changed {
 6474                                                    this.left_dock.update(cx, |dock, cx| {
 6475                                                        dock.clamp_panel_size(
 6476                                                            bounds.size.width,
 6477                                                            window,
 6478                                                            cx,
 6479                                                        )
 6480                                                    });
 6481
 6482                                                    this.right_dock.update(cx, |dock, cx| {
 6483                                                        dock.clamp_panel_size(
 6484                                                            bounds.size.width,
 6485                                                            window,
 6486                                                            cx,
 6487                                                        )
 6488                                                    });
 6489
 6490                                                    this.bottom_dock.update(cx, |dock, cx| {
 6491                                                        dock.clamp_panel_size(
 6492                                                            bounds.size.height,
 6493                                                            window,
 6494                                                            cx,
 6495                                                        )
 6496                                                    });
 6497                                                }
 6498                                            })
 6499                                        },
 6500                                        |_, _, _, _| {},
 6501                                    )
 6502                                    .absolute()
 6503                                    .size_full()
 6504                                })
 6505                                .when(self.zoomed.is_none(), |this| {
 6506                                    this.on_drag_move(cx.listener(
 6507                                        move |workspace,
 6508                                              e: &DragMoveEvent<DraggedDock>,
 6509                                              window,
 6510                                              cx| {
 6511                                            if workspace.previous_dock_drag_coordinates
 6512                                                != Some(e.event.position)
 6513                                            {
 6514                                                workspace.previous_dock_drag_coordinates =
 6515                                                    Some(e.event.position);
 6516                                                match e.drag(cx).0 {
 6517                                                    DockPosition::Left => {
 6518                                                        workspace.resize_left_dock(
 6519                                                            e.event.position.x
 6520                                                                - workspace.bounds.left(),
 6521                                                            window,
 6522                                                            cx,
 6523                                                        );
 6524                                                    }
 6525                                                    DockPosition::Right => {
 6526                                                        workspace.resize_right_dock(
 6527                                                            workspace.bounds.right()
 6528                                                                - e.event.position.x,
 6529                                                            window,
 6530                                                            cx,
 6531                                                        );
 6532                                                    }
 6533                                                    DockPosition::Bottom => {
 6534                                                        workspace.resize_bottom_dock(
 6535                                                            workspace.bounds.bottom()
 6536                                                                - e.event.position.y,
 6537                                                            window,
 6538                                                            cx,
 6539                                                        );
 6540                                                    }
 6541                                                };
 6542                                                workspace.serialize_workspace(window, cx);
 6543                                            }
 6544                                        },
 6545                                    ))
 6546                                })
 6547                                .child({
 6548                                    match bottom_dock_layout {
 6549                                        BottomDockLayout::Full => div()
 6550                                            .flex()
 6551                                            .flex_col()
 6552                                            .h_full()
 6553                                            .child(
 6554                                                div()
 6555                                                    .flex()
 6556                                                    .flex_row()
 6557                                                    .flex_1()
 6558                                                    .overflow_hidden()
 6559                                                    .children(self.render_dock(
 6560                                                        DockPosition::Left,
 6561                                                        &self.left_dock,
 6562                                                        window,
 6563                                                        cx,
 6564                                                    ))
 6565                                                    .child(
 6566                                                        div()
 6567                                                            .flex()
 6568                                                            .flex_col()
 6569                                                            .flex_1()
 6570                                                            .overflow_hidden()
 6571                                                            .child(
 6572                                                                h_flex()
 6573                                                                    .flex_1()
 6574                                                                    .when_some(
 6575                                                                        paddings.0,
 6576                                                                        |this, p| {
 6577                                                                            this.child(
 6578                                                                                p.border_r_1(),
 6579                                                                            )
 6580                                                                        },
 6581                                                                    )
 6582                                                                    .child(self.center.render(
 6583                                                                        self.zoomed.as_ref(),
 6584                                                                        &PaneRenderContext {
 6585                                                                            follower_states:
 6586                                                                                &self.follower_states,
 6587                                                                            active_call: self.active_call(),
 6588                                                                            active_pane: &self.active_pane,
 6589                                                                            app_state: &self.app_state,
 6590                                                                            project: &self.project,
 6591                                                                            workspace: &self.weak_self,
 6592                                                                        },
 6593                                                                        window,
 6594                                                                        cx,
 6595                                                                    ))
 6596                                                                    .when_some(
 6597                                                                        paddings.1,
 6598                                                                        |this, p| {
 6599                                                                            this.child(
 6600                                                                                p.border_l_1(),
 6601                                                                            )
 6602                                                                        },
 6603                                                                    ),
 6604                                                            ),
 6605                                                    )
 6606                                                    .children(self.render_dock(
 6607                                                        DockPosition::Right,
 6608                                                        &self.right_dock,
 6609                                                        window,
 6610                                                        cx,
 6611                                                    )),
 6612                                            )
 6613                                            .child(div().w_full().children(self.render_dock(
 6614                                                DockPosition::Bottom,
 6615                                                &self.bottom_dock,
 6616                                                window,
 6617                                                cx
 6618                                            ))),
 6619
 6620                                        BottomDockLayout::LeftAligned => div()
 6621                                            .flex()
 6622                                            .flex_row()
 6623                                            .h_full()
 6624                                            .child(
 6625                                                div()
 6626                                                    .flex()
 6627                                                    .flex_col()
 6628                                                    .flex_1()
 6629                                                    .h_full()
 6630                                                    .child(
 6631                                                        div()
 6632                                                            .flex()
 6633                                                            .flex_row()
 6634                                                            .flex_1()
 6635                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 6636                                                            .child(
 6637                                                                div()
 6638                                                                    .flex()
 6639                                                                    .flex_col()
 6640                                                                    .flex_1()
 6641                                                                    .overflow_hidden()
 6642                                                                    .child(
 6643                                                                        h_flex()
 6644                                                                            .flex_1()
 6645                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6646                                                                            .child(self.center.render(
 6647                                                                                self.zoomed.as_ref(),
 6648                                                                                &PaneRenderContext {
 6649                                                                                    follower_states:
 6650                                                                                        &self.follower_states,
 6651                                                                                    active_call: self.active_call(),
 6652                                                                                    active_pane: &self.active_pane,
 6653                                                                                    app_state: &self.app_state,
 6654                                                                                    project: &self.project,
 6655                                                                                    workspace: &self.weak_self,
 6656                                                                                },
 6657                                                                                window,
 6658                                                                                cx,
 6659                                                                            ))
 6660                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6661                                                                    )
 6662                                                            )
 6663                                                    )
 6664                                                    .child(
 6665                                                        div()
 6666                                                            .w_full()
 6667                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6668                                                    ),
 6669                                            )
 6670                                            .children(self.render_dock(
 6671                                                DockPosition::Right,
 6672                                                &self.right_dock,
 6673                                                window,
 6674                                                cx,
 6675                                            )),
 6676
 6677                                        BottomDockLayout::RightAligned => div()
 6678                                            .flex()
 6679                                            .flex_row()
 6680                                            .h_full()
 6681                                            .children(self.render_dock(
 6682                                                DockPosition::Left,
 6683                                                &self.left_dock,
 6684                                                window,
 6685                                                cx,
 6686                                            ))
 6687                                            .child(
 6688                                                div()
 6689                                                    .flex()
 6690                                                    .flex_col()
 6691                                                    .flex_1()
 6692                                                    .h_full()
 6693                                                    .child(
 6694                                                        div()
 6695                                                            .flex()
 6696                                                            .flex_row()
 6697                                                            .flex_1()
 6698                                                            .child(
 6699                                                                div()
 6700                                                                    .flex()
 6701                                                                    .flex_col()
 6702                                                                    .flex_1()
 6703                                                                    .overflow_hidden()
 6704                                                                    .child(
 6705                                                                        h_flex()
 6706                                                                            .flex_1()
 6707                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 6708                                                                            .child(self.center.render(
 6709                                                                                self.zoomed.as_ref(),
 6710                                                                                &PaneRenderContext {
 6711                                                                                    follower_states:
 6712                                                                                        &self.follower_states,
 6713                                                                                    active_call: self.active_call(),
 6714                                                                                    active_pane: &self.active_pane,
 6715                                                                                    app_state: &self.app_state,
 6716                                                                                    project: &self.project,
 6717                                                                                    workspace: &self.weak_self,
 6718                                                                                },
 6719                                                                                window,
 6720                                                                                cx,
 6721                                                                            ))
 6722                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 6723                                                                    )
 6724                                                            )
 6725                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 6726                                                    )
 6727                                                    .child(
 6728                                                        div()
 6729                                                            .w_full()
 6730                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 6731                                                    ),
 6732                                            ),
 6733
 6734                                        BottomDockLayout::Contained => div()
 6735                                            .flex()
 6736                                            .flex_row()
 6737                                            .h_full()
 6738                                            .children(self.render_dock(
 6739                                                DockPosition::Left,
 6740                                                &self.left_dock,
 6741                                                window,
 6742                                                cx,
 6743                                            ))
 6744                                            .child(
 6745                                                div()
 6746                                                    .flex()
 6747                                                    .flex_col()
 6748                                                    .flex_1()
 6749                                                    .overflow_hidden()
 6750                                                    .child(
 6751                                                        h_flex()
 6752                                                            .flex_1()
 6753                                                            .when_some(paddings.0, |this, p| {
 6754                                                                this.child(p.border_r_1())
 6755                                                            })
 6756                                                            .child(self.center.render(
 6757                                                                self.zoomed.as_ref(),
 6758                                                                &PaneRenderContext {
 6759                                                                    follower_states:
 6760                                                                        &self.follower_states,
 6761                                                                    active_call: self.active_call(),
 6762                                                                    active_pane: &self.active_pane,
 6763                                                                    app_state: &self.app_state,
 6764                                                                    project: &self.project,
 6765                                                                    workspace: &self.weak_self,
 6766                                                                },
 6767                                                                window,
 6768                                                                cx,
 6769                                                            ))
 6770                                                            .when_some(paddings.1, |this, p| {
 6771                                                                this.child(p.border_l_1())
 6772                                                            }),
 6773                                                    )
 6774                                                    .children(self.render_dock(
 6775                                                        DockPosition::Bottom,
 6776                                                        &self.bottom_dock,
 6777                                                        window,
 6778                                                        cx,
 6779                                                    )),
 6780                                            )
 6781                                            .children(self.render_dock(
 6782                                                DockPosition::Right,
 6783                                                &self.right_dock,
 6784                                                window,
 6785                                                cx,
 6786                                            )),
 6787                                    }
 6788                                })
 6789                                .children(self.zoomed.as_ref().and_then(|view| {
 6790                                    let zoomed_view = view.upgrade()?;
 6791                                    let div = div()
 6792                                        .occlude()
 6793                                        .absolute()
 6794                                        .overflow_hidden()
 6795                                        .border_color(colors.border)
 6796                                        .bg(colors.background)
 6797                                        .child(zoomed_view)
 6798                                        .inset_0()
 6799                                        .shadow_lg();
 6800
 6801                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 6802                                       return Some(div);
 6803                                    }
 6804
 6805                                    Some(match self.zoomed_position {
 6806                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 6807                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 6808                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 6809                                        None => {
 6810                                            div.top_2().bottom_2().left_2().right_2().border_1()
 6811                                        }
 6812                                    })
 6813                                }))
 6814                                .children(self.render_notifications(window, cx)),
 6815                        )
 6816                        .when(self.status_bar_visible(cx), |parent| {
 6817                            parent.child(self.status_bar.clone())
 6818                        })
 6819                        .child(self.modal_layer.clone())
 6820                        .child(self.toast_layer.clone()),
 6821                ),
 6822            window,
 6823            cx,
 6824        )
 6825    }
 6826}
 6827
 6828impl WorkspaceStore {
 6829    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 6830        Self {
 6831            workspaces: Default::default(),
 6832            _subscriptions: vec![
 6833                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 6834                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 6835            ],
 6836            client,
 6837        }
 6838    }
 6839
 6840    pub fn update_followers(
 6841        &self,
 6842        project_id: Option<u64>,
 6843        update: proto::update_followers::Variant,
 6844        cx: &App,
 6845    ) -> Option<()> {
 6846        let active_call = ActiveCall::try_global(cx)?;
 6847        let room_id = active_call.read(cx).room()?.read(cx).id();
 6848        self.client
 6849            .send(proto::UpdateFollowers {
 6850                room_id,
 6851                project_id,
 6852                variant: Some(update),
 6853            })
 6854            .log_err()
 6855    }
 6856
 6857    pub async fn handle_follow(
 6858        this: Entity<Self>,
 6859        envelope: TypedEnvelope<proto::Follow>,
 6860        mut cx: AsyncApp,
 6861    ) -> Result<proto::FollowResponse> {
 6862        this.update(&mut cx, |this, cx| {
 6863            let follower = Follower {
 6864                project_id: envelope.payload.project_id,
 6865                peer_id: envelope.original_sender_id()?,
 6866            };
 6867
 6868            let mut response = proto::FollowResponse::default();
 6869            this.workspaces.retain(|workspace| {
 6870                workspace
 6871                    .update(cx, |workspace, window, cx| {
 6872                        let handler_response =
 6873                            workspace.handle_follow(follower.project_id, window, cx);
 6874                        if let Some(active_view) = handler_response.active_view
 6875                            && workspace.project.read(cx).remote_id() == follower.project_id
 6876                        {
 6877                            response.active_view = Some(active_view)
 6878                        }
 6879                    })
 6880                    .is_ok()
 6881            });
 6882
 6883            Ok(response)
 6884        })?
 6885    }
 6886
 6887    async fn handle_update_followers(
 6888        this: Entity<Self>,
 6889        envelope: TypedEnvelope<proto::UpdateFollowers>,
 6890        mut cx: AsyncApp,
 6891    ) -> Result<()> {
 6892        let leader_id = envelope.original_sender_id()?;
 6893        let update = envelope.payload;
 6894
 6895        this.update(&mut cx, |this, cx| {
 6896            this.workspaces.retain(|workspace| {
 6897                workspace
 6898                    .update(cx, |workspace, window, cx| {
 6899                        let project_id = workspace.project.read(cx).remote_id();
 6900                        if update.project_id != project_id && update.project_id.is_some() {
 6901                            return;
 6902                        }
 6903                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 6904                    })
 6905                    .is_ok()
 6906            });
 6907            Ok(())
 6908        })?
 6909    }
 6910
 6911    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 6912        &self.workspaces
 6913    }
 6914}
 6915
 6916impl ViewId {
 6917    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 6918        Ok(Self {
 6919            creator: message
 6920                .creator
 6921                .map(CollaboratorId::PeerId)
 6922                .context("creator is missing")?,
 6923            id: message.id,
 6924        })
 6925    }
 6926
 6927    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 6928        if let CollaboratorId::PeerId(peer_id) = self.creator {
 6929            Some(proto::ViewId {
 6930                creator: Some(peer_id),
 6931                id: self.id,
 6932            })
 6933        } else {
 6934            None
 6935        }
 6936    }
 6937}
 6938
 6939impl FollowerState {
 6940    fn pane(&self) -> &Entity<Pane> {
 6941        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 6942    }
 6943}
 6944
 6945pub trait WorkspaceHandle {
 6946    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 6947}
 6948
 6949impl WorkspaceHandle for Entity<Workspace> {
 6950    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 6951        self.read(cx)
 6952            .worktrees(cx)
 6953            .flat_map(|worktree| {
 6954                let worktree_id = worktree.read(cx).id();
 6955                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 6956                    worktree_id,
 6957                    path: f.path.clone(),
 6958                })
 6959            })
 6960            .collect::<Vec<_>>()
 6961    }
 6962}
 6963
 6964pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 6965    DB.last_workspace().await.log_err().flatten()
 6966}
 6967
 6968pub fn last_session_workspace_locations(
 6969    last_session_id: &str,
 6970    last_session_window_stack: Option<Vec<WindowId>>,
 6971) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 6972    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 6973        .log_err()
 6974}
 6975
 6976actions!(
 6977    collab,
 6978    [
 6979        /// Opens the channel notes for the current call.
 6980        ///
 6981        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 6982        /// can be copied via "Copy link to section" in the context menu of the channel notes
 6983        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 6984        OpenChannelNotes,
 6985        /// Mutes your microphone.
 6986        Mute,
 6987        /// Deafens yourself (mute both microphone and speakers).
 6988        Deafen,
 6989        /// Leaves the current call.
 6990        LeaveCall,
 6991        /// Shares the current project with collaborators.
 6992        ShareProject,
 6993        /// Shares your screen with collaborators.
 6994        ScreenShare
 6995    ]
 6996);
 6997actions!(
 6998    zed,
 6999    [
 7000        /// Opens the Zed log file.
 7001        OpenLog
 7002    ]
 7003);
 7004
 7005async fn join_channel_internal(
 7006    channel_id: ChannelId,
 7007    app_state: &Arc<AppState>,
 7008    requesting_window: Option<WindowHandle<Workspace>>,
 7009    active_call: &Entity<ActiveCall>,
 7010    cx: &mut AsyncApp,
 7011) -> Result<bool> {
 7012    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7013        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7014            return (false, None);
 7015        };
 7016
 7017        let already_in_channel = room.channel_id() == Some(channel_id);
 7018        let should_prompt = room.is_sharing_project()
 7019            && !room.remote_participants().is_empty()
 7020            && !already_in_channel;
 7021        let open_room = if already_in_channel {
 7022            active_call.room().cloned()
 7023        } else {
 7024            None
 7025        };
 7026        (should_prompt, open_room)
 7027    })?;
 7028
 7029    if let Some(room) = open_room {
 7030        let task = room.update(cx, |room, cx| {
 7031            if let Some((project, host)) = room.most_active_project(cx) {
 7032                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7033            }
 7034
 7035            None
 7036        })?;
 7037        if let Some(task) = task {
 7038            task.await?;
 7039        }
 7040        return anyhow::Ok(true);
 7041    }
 7042
 7043    if should_prompt {
 7044        if let Some(workspace) = requesting_window {
 7045            let answer = workspace
 7046                .update(cx, |_, window, cx| {
 7047                    window.prompt(
 7048                        PromptLevel::Warning,
 7049                        "Do you want to switch channels?",
 7050                        Some("Leaving this call will unshare your current project."),
 7051                        &["Yes, Join Channel", "Cancel"],
 7052                        cx,
 7053                    )
 7054                })?
 7055                .await;
 7056
 7057            if answer == Ok(1) {
 7058                return Ok(false);
 7059            }
 7060        } else {
 7061            return Ok(false); // unreachable!() hopefully
 7062        }
 7063    }
 7064
 7065    let client = cx.update(|cx| active_call.read(cx).client())?;
 7066
 7067    let mut client_status = client.status();
 7068
 7069    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7070    'outer: loop {
 7071        let Some(status) = client_status.recv().await else {
 7072            anyhow::bail!("error connecting");
 7073        };
 7074
 7075        match status {
 7076            Status::Connecting
 7077            | Status::Authenticating
 7078            | Status::Authenticated
 7079            | Status::Reconnecting
 7080            | Status::Reauthenticating
 7081            | Status::Reauthenticated => continue,
 7082            Status::Connected { .. } => break 'outer,
 7083            Status::SignedOut | Status::AuthenticationError => {
 7084                return Err(ErrorCode::SignedOut.into());
 7085            }
 7086            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7087            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7088                return Err(ErrorCode::Disconnected.into());
 7089            }
 7090        }
 7091    }
 7092
 7093    let room = active_call
 7094        .update(cx, |active_call, cx| {
 7095            active_call.join_channel(channel_id, cx)
 7096        })?
 7097        .await?;
 7098
 7099    let Some(room) = room else {
 7100        return anyhow::Ok(true);
 7101    };
 7102
 7103    room.update(cx, |room, _| room.room_update_completed())?
 7104        .await;
 7105
 7106    let task = room.update(cx, |room, cx| {
 7107        if let Some((project, host)) = room.most_active_project(cx) {
 7108            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7109        }
 7110
 7111        // If you are the first to join a channel, see if you should share your project.
 7112        if room.remote_participants().is_empty()
 7113            && !room.local_participant_is_guest()
 7114            && let Some(workspace) = requesting_window
 7115        {
 7116            let project = workspace.update(cx, |workspace, _, cx| {
 7117                let project = workspace.project.read(cx);
 7118
 7119                if !CallSettings::get_global(cx).share_on_join {
 7120                    return None;
 7121                }
 7122
 7123                if (project.is_local() || project.is_via_remote_server())
 7124                    && project.visible_worktrees(cx).any(|tree| {
 7125                        tree.read(cx)
 7126                            .root_entry()
 7127                            .is_some_and(|entry| entry.is_dir())
 7128                    })
 7129                {
 7130                    Some(workspace.project.clone())
 7131                } else {
 7132                    None
 7133                }
 7134            });
 7135            if let Ok(Some(project)) = project {
 7136                return Some(cx.spawn(async move |room, cx| {
 7137                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7138                        .await?;
 7139                    Ok(())
 7140                }));
 7141            }
 7142        }
 7143
 7144        None
 7145    })?;
 7146    if let Some(task) = task {
 7147        task.await?;
 7148        return anyhow::Ok(true);
 7149    }
 7150    anyhow::Ok(false)
 7151}
 7152
 7153pub fn join_channel(
 7154    channel_id: ChannelId,
 7155    app_state: Arc<AppState>,
 7156    requesting_window: Option<WindowHandle<Workspace>>,
 7157    cx: &mut App,
 7158) -> Task<Result<()>> {
 7159    let active_call = ActiveCall::global(cx);
 7160    cx.spawn(async move |cx| {
 7161        let result = join_channel_internal(
 7162            channel_id,
 7163            &app_state,
 7164            requesting_window,
 7165            &active_call,
 7166             cx,
 7167        )
 7168            .await;
 7169
 7170        // join channel succeeded, and opened a window
 7171        if matches!(result, Ok(true)) {
 7172            return anyhow::Ok(());
 7173        }
 7174
 7175        // find an existing workspace to focus and show call controls
 7176        let mut active_window =
 7177            requesting_window.or_else(|| activate_any_workspace_window( cx));
 7178        if active_window.is_none() {
 7179            // no open workspaces, make one to show the error in (blergh)
 7180            let (window_handle, _) = cx
 7181                .update(|cx| {
 7182                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 7183                })?
 7184                .await?;
 7185
 7186            if result.is_ok() {
 7187                cx.update(|cx| {
 7188                    cx.dispatch_action(&OpenChannelNotes);
 7189                }).log_err();
 7190            }
 7191
 7192            active_window = Some(window_handle);
 7193        }
 7194
 7195        if let Err(err) = result {
 7196            log::error!("failed to join channel: {}", err);
 7197            if let Some(active_window) = active_window {
 7198                active_window
 7199                    .update(cx, |_, window, cx| {
 7200                        let detail: SharedString = match err.error_code() {
 7201                            ErrorCode::SignedOut => {
 7202                                "Please sign in to continue.".into()
 7203                            }
 7204                            ErrorCode::UpgradeRequired => {
 7205                                "Your are running an unsupported version of Zed. Please update to continue.".into()
 7206                            }
 7207                            ErrorCode::NoSuchChannel => {
 7208                                "No matching channel was found. Please check the link and try again.".into()
 7209                            }
 7210                            ErrorCode::Forbidden => {
 7211                                "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
 7212                            }
 7213                            ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
 7214                            _ => format!("{}\n\nPlease try again.", err).into(),
 7215                        };
 7216                        window.prompt(
 7217                            PromptLevel::Critical,
 7218                            "Failed to join channel",
 7219                            Some(&detail),
 7220                            &["Ok"],
 7221                        cx)
 7222                    })?
 7223                    .await
 7224                    .ok();
 7225            }
 7226        }
 7227
 7228        // return ok, we showed the error to the user.
 7229        anyhow::Ok(())
 7230    })
 7231}
 7232
 7233pub async fn get_any_active_workspace(
 7234    app_state: Arc<AppState>,
 7235    mut cx: AsyncApp,
 7236) -> anyhow::Result<WindowHandle<Workspace>> {
 7237    // find an existing workspace to focus and show call controls
 7238    let active_window = activate_any_workspace_window(&mut cx);
 7239    if active_window.is_none() {
 7240        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 7241            .await?;
 7242    }
 7243    activate_any_workspace_window(&mut cx).context("could not open zed")
 7244}
 7245
 7246fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7247    cx.update(|cx| {
 7248        if let Some(workspace_window) = cx
 7249            .active_window()
 7250            .and_then(|window| window.downcast::<Workspace>())
 7251        {
 7252            return Some(workspace_window);
 7253        }
 7254
 7255        for window in cx.windows() {
 7256            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7257                workspace_window
 7258                    .update(cx, |_, window, _| window.activate_window())
 7259                    .ok();
 7260                return Some(workspace_window);
 7261            }
 7262        }
 7263        None
 7264    })
 7265    .ok()
 7266    .flatten()
 7267}
 7268
 7269pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7270    cx.windows()
 7271        .into_iter()
 7272        .filter_map(|window| window.downcast::<Workspace>())
 7273        .filter(|workspace| {
 7274            workspace
 7275                .read(cx)
 7276                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7277        })
 7278        .collect()
 7279}
 7280
 7281#[derive(Default)]
 7282pub struct OpenOptions {
 7283    pub visible: Option<OpenVisible>,
 7284    pub focus: Option<bool>,
 7285    pub open_new_workspace: Option<bool>,
 7286    pub replace_window: Option<WindowHandle<Workspace>>,
 7287    pub env: Option<HashMap<String, String>>,
 7288}
 7289
 7290#[allow(clippy::type_complexity)]
 7291pub fn open_paths(
 7292    abs_paths: &[PathBuf],
 7293    app_state: Arc<AppState>,
 7294    open_options: OpenOptions,
 7295    cx: &mut App,
 7296) -> Task<
 7297    anyhow::Result<(
 7298        WindowHandle<Workspace>,
 7299        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7300    )>,
 7301> {
 7302    let abs_paths = abs_paths.to_vec();
 7303    let mut existing = None;
 7304    let mut best_match = None;
 7305    let mut open_visible = OpenVisible::All;
 7306
 7307    cx.spawn(async move |cx| {
 7308        if open_options.open_new_workspace != Some(true) {
 7309            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7310            let all_metadatas = futures::future::join_all(all_paths)
 7311                .await
 7312                .into_iter()
 7313                .filter_map(|result| result.ok().flatten())
 7314                .collect::<Vec<_>>();
 7315
 7316            cx.update(|cx| {
 7317                for window in local_workspace_windows(cx) {
 7318                    if let Ok(workspace) = window.read(cx) {
 7319                        let m = workspace.project.read(cx).visibility_for_paths(
 7320                            &abs_paths,
 7321                            &all_metadatas,
 7322                            open_options.open_new_workspace == None,
 7323                            cx,
 7324                        );
 7325                        if m > best_match {
 7326                            existing = Some(window);
 7327                            best_match = m;
 7328                        } else if best_match.is_none()
 7329                            && open_options.open_new_workspace == Some(false)
 7330                        {
 7331                            existing = Some(window)
 7332                        }
 7333                    }
 7334                }
 7335            })?;
 7336
 7337            if open_options.open_new_workspace.is_none()
 7338                && existing.is_none()
 7339                && all_metadatas.iter().all(|file| !file.is_dir)
 7340            {
 7341                cx.update(|cx| {
 7342                    if let Some(window) = cx
 7343                        .active_window()
 7344                        .and_then(|window| window.downcast::<Workspace>())
 7345                        && let Ok(workspace) = window.read(cx)
 7346                    {
 7347                        let project = workspace.project().read(cx);
 7348                        if project.is_local() && !project.is_via_collab() {
 7349                            existing = Some(window);
 7350                            open_visible = OpenVisible::None;
 7351                            return;
 7352                        }
 7353                    }
 7354                    for window in local_workspace_windows(cx) {
 7355                        if let Ok(workspace) = window.read(cx) {
 7356                            let project = workspace.project().read(cx);
 7357                            if project.is_via_collab() {
 7358                                continue;
 7359                            }
 7360                            existing = Some(window);
 7361                            open_visible = OpenVisible::None;
 7362                            break;
 7363                        }
 7364                    }
 7365                })?;
 7366            }
 7367        }
 7368
 7369        if let Some(existing) = existing {
 7370            let open_task = existing
 7371                .update(cx, |workspace, window, cx| {
 7372                    window.activate_window();
 7373                    workspace.open_paths(
 7374                        abs_paths,
 7375                        OpenOptions {
 7376                            visible: Some(open_visible),
 7377                            ..Default::default()
 7378                        },
 7379                        None,
 7380                        window,
 7381                        cx,
 7382                    )
 7383                })?
 7384                .await;
 7385
 7386            _ = existing.update(cx, |workspace, _, cx| {
 7387                for item in open_task.iter().flatten() {
 7388                    if let Err(e) = item {
 7389                        workspace.show_error(&e, cx);
 7390                    }
 7391                }
 7392            });
 7393
 7394            Ok((existing, open_task))
 7395        } else {
 7396            cx.update(move |cx| {
 7397                Workspace::new_local(
 7398                    abs_paths,
 7399                    app_state.clone(),
 7400                    open_options.replace_window,
 7401                    open_options.env,
 7402                    cx,
 7403                )
 7404            })?
 7405            .await
 7406        }
 7407    })
 7408}
 7409
 7410pub fn open_new(
 7411    open_options: OpenOptions,
 7412    app_state: Arc<AppState>,
 7413    cx: &mut App,
 7414    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7415) -> Task<anyhow::Result<()>> {
 7416    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7417    cx.spawn(async move |cx| {
 7418        let (workspace, opened_paths) = task.await?;
 7419        workspace.update(cx, |workspace, window, cx| {
 7420            if opened_paths.is_empty() {
 7421                init(workspace, window, cx)
 7422            }
 7423        })?;
 7424        Ok(())
 7425    })
 7426}
 7427
 7428pub fn create_and_open_local_file(
 7429    path: &'static Path,
 7430    window: &mut Window,
 7431    cx: &mut Context<Workspace>,
 7432    default_content: impl 'static + Send + FnOnce() -> Rope,
 7433) -> Task<Result<Box<dyn ItemHandle>>> {
 7434    cx.spawn_in(window, async move |workspace, cx| {
 7435        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7436        if !fs.is_file(path).await {
 7437            fs.create_file(path, Default::default()).await?;
 7438            fs.save(path, &default_content(), Default::default())
 7439                .await?;
 7440        }
 7441
 7442        let mut items = workspace
 7443            .update_in(cx, |workspace, window, cx| {
 7444                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7445                    workspace.open_paths(
 7446                        vec![path.to_path_buf()],
 7447                        OpenOptions {
 7448                            visible: Some(OpenVisible::None),
 7449                            ..Default::default()
 7450                        },
 7451                        None,
 7452                        window,
 7453                        cx,
 7454                    )
 7455                })
 7456            })?
 7457            .await?
 7458            .await;
 7459
 7460        let item = items.pop().flatten();
 7461        item.with_context(|| format!("path {path:?} is not a file"))?
 7462    })
 7463}
 7464
 7465pub fn open_remote_project_with_new_connection(
 7466    window: WindowHandle<Workspace>,
 7467    remote_connection: Arc<dyn RemoteConnection>,
 7468    cancel_rx: oneshot::Receiver<()>,
 7469    delegate: Arc<dyn RemoteClientDelegate>,
 7470    app_state: Arc<AppState>,
 7471    paths: Vec<PathBuf>,
 7472    cx: &mut App,
 7473) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7474    cx.spawn(async move |cx| {
 7475        let (workspace_id, serialized_workspace) =
 7476            serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 7477                .await?;
 7478
 7479        let session = match cx
 7480            .update(|cx| {
 7481                remote::RemoteClient::new(
 7482                    ConnectionIdentifier::Workspace(workspace_id.0),
 7483                    remote_connection,
 7484                    cancel_rx,
 7485                    delegate,
 7486                    cx,
 7487                )
 7488            })?
 7489            .await?
 7490        {
 7491            Some(result) => result,
 7492            None => return Ok(Vec::new()),
 7493        };
 7494
 7495        let project = cx.update(|cx| {
 7496            project::Project::remote(
 7497                session,
 7498                app_state.client.clone(),
 7499                app_state.node_runtime.clone(),
 7500                app_state.user_store.clone(),
 7501                app_state.languages.clone(),
 7502                app_state.fs.clone(),
 7503                cx,
 7504            )
 7505        })?;
 7506
 7507        open_remote_project_inner(
 7508            project,
 7509            paths,
 7510            workspace_id,
 7511            serialized_workspace,
 7512            app_state,
 7513            window,
 7514            cx,
 7515        )
 7516        .await
 7517    })
 7518}
 7519
 7520pub fn open_remote_project_with_existing_connection(
 7521    connection_options: RemoteConnectionOptions,
 7522    project: Entity<Project>,
 7523    paths: Vec<PathBuf>,
 7524    app_state: Arc<AppState>,
 7525    window: WindowHandle<Workspace>,
 7526    cx: &mut AsyncApp,
 7527) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7528    cx.spawn(async move |cx| {
 7529        let (workspace_id, serialized_workspace) =
 7530            serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7531
 7532        open_remote_project_inner(
 7533            project,
 7534            paths,
 7535            workspace_id,
 7536            serialized_workspace,
 7537            app_state,
 7538            window,
 7539            cx,
 7540        )
 7541        .await
 7542    })
 7543}
 7544
 7545async fn open_remote_project_inner(
 7546    project: Entity<Project>,
 7547    paths: Vec<PathBuf>,
 7548    workspace_id: WorkspaceId,
 7549    serialized_workspace: Option<SerializedWorkspace>,
 7550    app_state: Arc<AppState>,
 7551    window: WindowHandle<Workspace>,
 7552    cx: &mut AsyncApp,
 7553) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 7554    let toolchains = DB.toolchains(workspace_id).await?;
 7555    for (toolchain, worktree_id, path) in toolchains {
 7556        project
 7557            .update(cx, |this, cx| {
 7558                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 7559            })?
 7560            .await;
 7561    }
 7562    let mut project_paths_to_open = vec![];
 7563    let mut project_path_errors = vec![];
 7564
 7565    for path in paths {
 7566        let result = cx
 7567            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 7568            .await;
 7569        match result {
 7570            Ok((_, project_path)) => {
 7571                project_paths_to_open.push((path.clone(), Some(project_path)));
 7572            }
 7573            Err(error) => {
 7574                project_path_errors.push(error);
 7575            }
 7576        };
 7577    }
 7578
 7579    if project_paths_to_open.is_empty() {
 7580        return Err(project_path_errors.pop().context("no paths given")?);
 7581    }
 7582
 7583    if let Some(detach_session_task) = window
 7584        .update(cx, |_workspace, window, cx| {
 7585            cx.spawn_in(window, async move |this, cx| {
 7586                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 7587            })
 7588        })
 7589        .ok()
 7590    {
 7591        detach_session_task.await.ok();
 7592    }
 7593
 7594    cx.update_window(window.into(), |_, window, cx| {
 7595        window.replace_root(cx, |window, cx| {
 7596            telemetry::event!("SSH Project Opened");
 7597
 7598            let mut workspace =
 7599                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 7600            workspace.update_history(cx);
 7601
 7602            if let Some(ref serialized) = serialized_workspace {
 7603                workspace.centered_layout = serialized.centered_layout;
 7604            }
 7605
 7606            workspace
 7607        });
 7608    })?;
 7609
 7610    let items = window
 7611        .update(cx, |_, window, cx| {
 7612            window.activate_window();
 7613            open_items(serialized_workspace, project_paths_to_open, window, cx)
 7614        })?
 7615        .await?;
 7616
 7617    window.update(cx, |workspace, _, cx| {
 7618        for error in project_path_errors {
 7619            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 7620                if let Some(path) = error.error_tag("path") {
 7621                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 7622                }
 7623            } else {
 7624                workspace.show_error(&error, cx)
 7625            }
 7626        }
 7627    })?;
 7628
 7629    Ok(items.into_iter().map(|item| item?.ok()).collect())
 7630}
 7631
 7632fn serialize_remote_project(
 7633    connection_options: RemoteConnectionOptions,
 7634    paths: Vec<PathBuf>,
 7635    cx: &AsyncApp,
 7636) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7637    cx.background_spawn(async move {
 7638        let remote_connection_id = persistence::DB
 7639            .get_or_create_remote_connection(connection_options)
 7640            .await?;
 7641
 7642        let serialized_workspace =
 7643            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 7644
 7645        let workspace_id = if let Some(workspace_id) =
 7646            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7647        {
 7648            workspace_id
 7649        } else {
 7650            persistence::DB.next_id().await?
 7651        };
 7652
 7653        Ok((workspace_id, serialized_workspace))
 7654    })
 7655}
 7656
 7657pub fn join_in_room_project(
 7658    project_id: u64,
 7659    follow_user_id: u64,
 7660    app_state: Arc<AppState>,
 7661    cx: &mut App,
 7662) -> Task<Result<()>> {
 7663    let windows = cx.windows();
 7664    cx.spawn(async move |cx| {
 7665        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7666            window_handle
 7667                .downcast::<Workspace>()
 7668                .and_then(|window_handle| {
 7669                    window_handle
 7670                        .update(cx, |workspace, _window, cx| {
 7671                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7672                                Some(window_handle)
 7673                            } else {
 7674                                None
 7675                            }
 7676                        })
 7677                        .unwrap_or(None)
 7678                })
 7679        });
 7680
 7681        let workspace = if let Some(existing_workspace) = existing_workspace {
 7682            existing_workspace
 7683        } else {
 7684            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7685            let room = active_call
 7686                .read_with(cx, |call, _| call.room().cloned())?
 7687                .context("not in a call")?;
 7688            let project = room
 7689                .update(cx, |room, cx| {
 7690                    room.join_project(
 7691                        project_id,
 7692                        app_state.languages.clone(),
 7693                        app_state.fs.clone(),
 7694                        cx,
 7695                    )
 7696                })?
 7697                .await?;
 7698
 7699            let window_bounds_override = window_bounds_env_override();
 7700            cx.update(|cx| {
 7701                let mut options = (app_state.build_window_options)(None, cx);
 7702                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7703                cx.open_window(options, |window, cx| {
 7704                    cx.new(|cx| {
 7705                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7706                    })
 7707                })
 7708            })??
 7709        };
 7710
 7711        workspace.update(cx, |workspace, window, cx| {
 7712            cx.activate(true);
 7713            window.activate_window();
 7714
 7715            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7716                let follow_peer_id = room
 7717                    .read(cx)
 7718                    .remote_participants()
 7719                    .iter()
 7720                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7721                    .map(|(_, p)| p.peer_id)
 7722                    .or_else(|| {
 7723                        // If we couldn't follow the given user, follow the host instead.
 7724                        let collaborator = workspace
 7725                            .project()
 7726                            .read(cx)
 7727                            .collaborators()
 7728                            .values()
 7729                            .find(|collaborator| collaborator.is_host)?;
 7730                        Some(collaborator.peer_id)
 7731                    });
 7732
 7733                if let Some(follow_peer_id) = follow_peer_id {
 7734                    workspace.follow(follow_peer_id, window, cx);
 7735                }
 7736            }
 7737        })?;
 7738
 7739        anyhow::Ok(())
 7740    })
 7741}
 7742
 7743pub fn reload(cx: &mut App) {
 7744    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7745    let mut workspace_windows = cx
 7746        .windows()
 7747        .into_iter()
 7748        .filter_map(|window| window.downcast::<Workspace>())
 7749        .collect::<Vec<_>>();
 7750
 7751    // If multiple windows have unsaved changes, and need a save prompt,
 7752    // prompt in the active window before switching to a different window.
 7753    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7754
 7755    let mut prompt = None;
 7756    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7757        prompt = window
 7758            .update(cx, |_, window, cx| {
 7759                window.prompt(
 7760                    PromptLevel::Info,
 7761                    "Are you sure you want to restart?",
 7762                    None,
 7763                    &["Restart", "Cancel"],
 7764                    cx,
 7765                )
 7766            })
 7767            .ok();
 7768    }
 7769
 7770    cx.spawn(async move |cx| {
 7771        if let Some(prompt) = prompt {
 7772            let answer = prompt.await?;
 7773            if answer != 0 {
 7774                return Ok(());
 7775            }
 7776        }
 7777
 7778        // If the user cancels any save prompt, then keep the app open.
 7779        for window in workspace_windows {
 7780            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7781                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7782            }) && !should_close.await?
 7783            {
 7784                return Ok(());
 7785            }
 7786        }
 7787        cx.update(|cx| cx.restart())
 7788    })
 7789    .detach_and_log_err(cx);
 7790}
 7791
 7792fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7793    let mut parts = value.split(',');
 7794    let x: usize = parts.next()?.parse().ok()?;
 7795    let y: usize = parts.next()?.parse().ok()?;
 7796    Some(point(px(x as f32), px(y as f32)))
 7797}
 7798
 7799fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7800    let mut parts = value.split(',');
 7801    let width: usize = parts.next()?.parse().ok()?;
 7802    let height: usize = parts.next()?.parse().ok()?;
 7803    Some(size(px(width as f32), px(height as f32)))
 7804}
 7805
 7806/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7807pub fn client_side_decorations(
 7808    element: impl IntoElement,
 7809    window: &mut Window,
 7810    cx: &mut App,
 7811) -> Stateful<Div> {
 7812    const BORDER_SIZE: Pixels = px(1.0);
 7813    let decorations = window.window_decorations();
 7814
 7815    match decorations {
 7816        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7817        Decorations::Server => window.set_client_inset(px(0.0)),
 7818    }
 7819
 7820    struct GlobalResizeEdge(ResizeEdge);
 7821    impl Global for GlobalResizeEdge {}
 7822
 7823    div()
 7824        .id("window-backdrop")
 7825        .bg(transparent_black())
 7826        .map(|div| match decorations {
 7827            Decorations::Server => div,
 7828            Decorations::Client { tiling, .. } => div
 7829                .when(!(tiling.top || tiling.right), |div| {
 7830                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7831                })
 7832                .when(!(tiling.top || tiling.left), |div| {
 7833                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7834                })
 7835                .when(!(tiling.bottom || tiling.right), |div| {
 7836                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7837                })
 7838                .when(!(tiling.bottom || tiling.left), |div| {
 7839                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7840                })
 7841                .when(!tiling.top, |div| {
 7842                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7843                })
 7844                .when(!tiling.bottom, |div| {
 7845                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7846                })
 7847                .when(!tiling.left, |div| {
 7848                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7849                })
 7850                .when(!tiling.right, |div| {
 7851                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7852                })
 7853                .on_mouse_move(move |e, window, cx| {
 7854                    let size = window.window_bounds().get_bounds().size;
 7855                    let pos = e.position;
 7856
 7857                    let new_edge =
 7858                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 7859
 7860                    let edge = cx.try_global::<GlobalResizeEdge>();
 7861                    if new_edge != edge.map(|edge| edge.0) {
 7862                        window
 7863                            .window_handle()
 7864                            .update(cx, |workspace, _, cx| {
 7865                                cx.notify(workspace.entity_id());
 7866                            })
 7867                            .ok();
 7868                    }
 7869                })
 7870                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 7871                    let size = window.window_bounds().get_bounds().size;
 7872                    let pos = e.position;
 7873
 7874                    let edge = match resize_edge(
 7875                        pos,
 7876                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 7877                        size,
 7878                        tiling,
 7879                    ) {
 7880                        Some(value) => value,
 7881                        None => return,
 7882                    };
 7883
 7884                    window.start_window_resize(edge);
 7885                }),
 7886        })
 7887        .size_full()
 7888        .child(
 7889            div()
 7890                .cursor(CursorStyle::Arrow)
 7891                .map(|div| match decorations {
 7892                    Decorations::Server => div,
 7893                    Decorations::Client { tiling } => div
 7894                        .border_color(cx.theme().colors().border)
 7895                        .when(!(tiling.top || tiling.right), |div| {
 7896                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7897                        })
 7898                        .when(!(tiling.top || tiling.left), |div| {
 7899                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7900                        })
 7901                        .when(!(tiling.bottom || tiling.right), |div| {
 7902                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7903                        })
 7904                        .when(!(tiling.bottom || tiling.left), |div| {
 7905                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7906                        })
 7907                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 7908                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 7909                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 7910                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 7911                        .when(!tiling.is_tiled(), |div| {
 7912                            div.shadow(vec![gpui::BoxShadow {
 7913                                color: Hsla {
 7914                                    h: 0.,
 7915                                    s: 0.,
 7916                                    l: 0.,
 7917                                    a: 0.4,
 7918                                },
 7919                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 7920                                spread_radius: px(0.),
 7921                                offset: point(px(0.0), px(0.0)),
 7922                            }])
 7923                        }),
 7924                })
 7925                .on_mouse_move(|_e, _, cx| {
 7926                    cx.stop_propagation();
 7927                })
 7928                .size_full()
 7929                .child(element),
 7930        )
 7931        .map(|div| match decorations {
 7932            Decorations::Server => div,
 7933            Decorations::Client { tiling, .. } => div.child(
 7934                canvas(
 7935                    |_bounds, window, _| {
 7936                        window.insert_hitbox(
 7937                            Bounds::new(
 7938                                point(px(0.0), px(0.0)),
 7939                                window.window_bounds().get_bounds().size,
 7940                            ),
 7941                            HitboxBehavior::Normal,
 7942                        )
 7943                    },
 7944                    move |_bounds, hitbox, window, cx| {
 7945                        let mouse = window.mouse_position();
 7946                        let size = window.window_bounds().get_bounds().size;
 7947                        let Some(edge) =
 7948                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 7949                        else {
 7950                            return;
 7951                        };
 7952                        cx.set_global(GlobalResizeEdge(edge));
 7953                        window.set_cursor_style(
 7954                            match edge {
 7955                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 7956                                ResizeEdge::Left | ResizeEdge::Right => {
 7957                                    CursorStyle::ResizeLeftRight
 7958                                }
 7959                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 7960                                    CursorStyle::ResizeUpLeftDownRight
 7961                                }
 7962                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 7963                                    CursorStyle::ResizeUpRightDownLeft
 7964                                }
 7965                            },
 7966                            &hitbox,
 7967                        );
 7968                    },
 7969                )
 7970                .size_full()
 7971                .absolute(),
 7972            ),
 7973        })
 7974}
 7975
 7976fn resize_edge(
 7977    pos: Point<Pixels>,
 7978    shadow_size: Pixels,
 7979    window_size: Size<Pixels>,
 7980    tiling: Tiling,
 7981) -> Option<ResizeEdge> {
 7982    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 7983    if bounds.contains(&pos) {
 7984        return None;
 7985    }
 7986
 7987    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 7988    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 7989    if !tiling.top && top_left_bounds.contains(&pos) {
 7990        return Some(ResizeEdge::TopLeft);
 7991    }
 7992
 7993    let top_right_bounds = Bounds::new(
 7994        Point::new(window_size.width - corner_size.width, px(0.)),
 7995        corner_size,
 7996    );
 7997    if !tiling.top && top_right_bounds.contains(&pos) {
 7998        return Some(ResizeEdge::TopRight);
 7999    }
 8000
 8001    let bottom_left_bounds = Bounds::new(
 8002        Point::new(px(0.), window_size.height - corner_size.height),
 8003        corner_size,
 8004    );
 8005    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8006        return Some(ResizeEdge::BottomLeft);
 8007    }
 8008
 8009    let bottom_right_bounds = Bounds::new(
 8010        Point::new(
 8011            window_size.width - corner_size.width,
 8012            window_size.height - corner_size.height,
 8013        ),
 8014        corner_size,
 8015    );
 8016    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8017        return Some(ResizeEdge::BottomRight);
 8018    }
 8019
 8020    if !tiling.top && pos.y < shadow_size {
 8021        Some(ResizeEdge::Top)
 8022    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8023        Some(ResizeEdge::Bottom)
 8024    } else if !tiling.left && pos.x < shadow_size {
 8025        Some(ResizeEdge::Left)
 8026    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8027        Some(ResizeEdge::Right)
 8028    } else {
 8029        None
 8030    }
 8031}
 8032
 8033fn join_pane_into_active(
 8034    active_pane: &Entity<Pane>,
 8035    pane: &Entity<Pane>,
 8036    window: &mut Window,
 8037    cx: &mut App,
 8038) {
 8039    if pane == active_pane {
 8040    } else if pane.read(cx).items_len() == 0 {
 8041        pane.update(cx, |_, cx| {
 8042            cx.emit(pane::Event::Remove {
 8043                focus_on_pane: None,
 8044            });
 8045        })
 8046    } else {
 8047        move_all_items(pane, active_pane, window, cx);
 8048    }
 8049}
 8050
 8051fn move_all_items(
 8052    from_pane: &Entity<Pane>,
 8053    to_pane: &Entity<Pane>,
 8054    window: &mut Window,
 8055    cx: &mut App,
 8056) {
 8057    let destination_is_different = from_pane != to_pane;
 8058    let mut moved_items = 0;
 8059    for (item_ix, item_handle) in from_pane
 8060        .read(cx)
 8061        .items()
 8062        .enumerate()
 8063        .map(|(ix, item)| (ix, item.clone()))
 8064        .collect::<Vec<_>>()
 8065    {
 8066        let ix = item_ix - moved_items;
 8067        if destination_is_different {
 8068            // Close item from previous pane
 8069            from_pane.update(cx, |source, cx| {
 8070                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8071            });
 8072            moved_items += 1;
 8073        }
 8074
 8075        // This automatically removes duplicate items in the pane
 8076        to_pane.update(cx, |destination, cx| {
 8077            destination.add_item(item_handle, true, true, None, window, cx);
 8078            window.focus(&destination.focus_handle(cx))
 8079        });
 8080    }
 8081}
 8082
 8083pub fn move_item(
 8084    source: &Entity<Pane>,
 8085    destination: &Entity<Pane>,
 8086    item_id_to_move: EntityId,
 8087    destination_index: usize,
 8088    activate: bool,
 8089    window: &mut Window,
 8090    cx: &mut App,
 8091) {
 8092    let Some((item_ix, item_handle)) = source
 8093        .read(cx)
 8094        .items()
 8095        .enumerate()
 8096        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8097        .map(|(ix, item)| (ix, item.clone()))
 8098    else {
 8099        // Tab was closed during drag
 8100        return;
 8101    };
 8102
 8103    if source != destination {
 8104        // Close item from previous pane
 8105        source.update(cx, |source, cx| {
 8106            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8107        });
 8108    }
 8109
 8110    // This automatically removes duplicate items in the pane
 8111    destination.update(cx, |destination, cx| {
 8112        destination.add_item_inner(
 8113            item_handle,
 8114            activate,
 8115            activate,
 8116            activate,
 8117            Some(destination_index),
 8118            window,
 8119            cx,
 8120        );
 8121        if activate {
 8122            window.focus(&destination.focus_handle(cx))
 8123        }
 8124    });
 8125}
 8126
 8127pub fn move_active_item(
 8128    source: &Entity<Pane>,
 8129    destination: &Entity<Pane>,
 8130    focus_destination: bool,
 8131    close_if_empty: bool,
 8132    window: &mut Window,
 8133    cx: &mut App,
 8134) {
 8135    if source == destination {
 8136        return;
 8137    }
 8138    let Some(active_item) = source.read(cx).active_item() else {
 8139        return;
 8140    };
 8141    source.update(cx, |source_pane, cx| {
 8142        let item_id = active_item.item_id();
 8143        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8144        destination.update(cx, |target_pane, cx| {
 8145            target_pane.add_item(
 8146                active_item,
 8147                focus_destination,
 8148                focus_destination,
 8149                Some(target_pane.items_len()),
 8150                window,
 8151                cx,
 8152            );
 8153        });
 8154    });
 8155}
 8156
 8157pub fn clone_active_item(
 8158    workspace_id: Option<WorkspaceId>,
 8159    source: &Entity<Pane>,
 8160    destination: &Entity<Pane>,
 8161    focus_destination: bool,
 8162    window: &mut Window,
 8163    cx: &mut App,
 8164) {
 8165    if source == destination {
 8166        return;
 8167    }
 8168    let Some(active_item) = source.read(cx).active_item() else {
 8169        return;
 8170    };
 8171    destination.update(cx, |target_pane, cx| {
 8172        let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
 8173            return;
 8174        };
 8175        target_pane.add_item(
 8176            clone,
 8177            focus_destination,
 8178            focus_destination,
 8179            Some(target_pane.items_len()),
 8180            window,
 8181            cx,
 8182        );
 8183    });
 8184}
 8185
 8186#[derive(Debug)]
 8187pub struct WorkspacePosition {
 8188    pub window_bounds: Option<WindowBounds>,
 8189    pub display: Option<Uuid>,
 8190    pub centered_layout: bool,
 8191}
 8192
 8193pub fn remote_workspace_position_from_db(
 8194    connection_options: RemoteConnectionOptions,
 8195    paths_to_open: &[PathBuf],
 8196    cx: &App,
 8197) -> Task<Result<WorkspacePosition>> {
 8198    let paths = paths_to_open.to_vec();
 8199
 8200    cx.background_spawn(async move {
 8201        let remote_connection_id = persistence::DB
 8202            .get_or_create_remote_connection(connection_options)
 8203            .await
 8204            .context("fetching serialized ssh project")?;
 8205        let serialized_workspace =
 8206            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8207
 8208        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8209            (Some(WindowBounds::Windowed(bounds)), None)
 8210        } else {
 8211            let restorable_bounds = serialized_workspace
 8212                .as_ref()
 8213                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8214                .or_else(|| {
 8215                    let (display, window_bounds) = DB.last_window().log_err()?;
 8216                    Some((display?, window_bounds?))
 8217                });
 8218
 8219            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8220                (Some(serialized_status.0), Some(serialized_display))
 8221            } else {
 8222                (None, None)
 8223            }
 8224        };
 8225
 8226        let centered_layout = serialized_workspace
 8227            .as_ref()
 8228            .map(|w| w.centered_layout)
 8229            .unwrap_or(false);
 8230
 8231        Ok(WorkspacePosition {
 8232            window_bounds,
 8233            display,
 8234            centered_layout,
 8235        })
 8236    })
 8237}
 8238
 8239pub fn with_active_or_new_workspace(
 8240    cx: &mut App,
 8241    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8242) {
 8243    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8244        Some(workspace) => {
 8245            cx.defer(move |cx| {
 8246                workspace
 8247                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8248                    .log_err();
 8249            });
 8250        }
 8251        None => {
 8252            let app_state = AppState::global(cx);
 8253            if let Some(app_state) = app_state.upgrade() {
 8254                open_new(
 8255                    OpenOptions::default(),
 8256                    app_state,
 8257                    cx,
 8258                    move |workspace, window, cx| f(workspace, window, cx),
 8259                )
 8260                .detach_and_log_err(cx);
 8261            }
 8262        }
 8263    }
 8264}
 8265
 8266#[cfg(test)]
 8267mod tests {
 8268    use std::{cell::RefCell, rc::Rc};
 8269
 8270    use super::*;
 8271    use crate::{
 8272        dock::{PanelEvent, test::TestPanel},
 8273        item::{
 8274            ItemBufferKind, ItemEvent,
 8275            test::{TestItem, TestProjectItem},
 8276        },
 8277    };
 8278    use fs::FakeFs;
 8279    use gpui::{
 8280        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8281        UpdateGlobal, VisualTestContext, px,
 8282    };
 8283    use project::{Project, ProjectEntryId};
 8284    use serde_json::json;
 8285    use settings::SettingsStore;
 8286    use util::rel_path::rel_path;
 8287
 8288    #[gpui::test]
 8289    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8290        init_test(cx);
 8291
 8292        let fs = FakeFs::new(cx.executor());
 8293        let project = Project::test(fs, [], cx).await;
 8294        let (workspace, cx) =
 8295            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8296
 8297        // Adding an item with no ambiguity renders the tab without detail.
 8298        let item1 = cx.new(|cx| {
 8299            let mut item = TestItem::new(cx);
 8300            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8301            item
 8302        });
 8303        workspace.update_in(cx, |workspace, window, cx| {
 8304            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8305        });
 8306        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8307
 8308        // Adding an item that creates ambiguity increases the level of detail on
 8309        // both tabs.
 8310        let item2 = cx.new_window_entity(|_window, cx| {
 8311            let mut item = TestItem::new(cx);
 8312            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8313            item
 8314        });
 8315        workspace.update_in(cx, |workspace, window, cx| {
 8316            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8317        });
 8318        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8319        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8320
 8321        // Adding an item that creates ambiguity increases the level of detail only
 8322        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8323        // we stop at the highest detail available.
 8324        let item3 = cx.new(|cx| {
 8325            let mut item = TestItem::new(cx);
 8326            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8327            item
 8328        });
 8329        workspace.update_in(cx, |workspace, window, cx| {
 8330            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8331        });
 8332        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8333        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8334        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8335    }
 8336
 8337    #[gpui::test]
 8338    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8339        init_test(cx);
 8340
 8341        let fs = FakeFs::new(cx.executor());
 8342        fs.insert_tree(
 8343            "/root1",
 8344            json!({
 8345                "one.txt": "",
 8346                "two.txt": "",
 8347            }),
 8348        )
 8349        .await;
 8350        fs.insert_tree(
 8351            "/root2",
 8352            json!({
 8353                "three.txt": "",
 8354            }),
 8355        )
 8356        .await;
 8357
 8358        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8359        let (workspace, cx) =
 8360            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8361        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8362        let worktree_id = project.update(cx, |project, cx| {
 8363            project.worktrees(cx).next().unwrap().read(cx).id()
 8364        });
 8365
 8366        let item1 = cx.new(|cx| {
 8367            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8368        });
 8369        let item2 = cx.new(|cx| {
 8370            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8371        });
 8372
 8373        // Add an item to an empty pane
 8374        workspace.update_in(cx, |workspace, window, cx| {
 8375            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8376        });
 8377        project.update(cx, |project, cx| {
 8378            assert_eq!(
 8379                project.active_entry(),
 8380                project
 8381                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8382                    .map(|e| e.id)
 8383            );
 8384        });
 8385        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8386
 8387        // Add a second item to a non-empty pane
 8388        workspace.update_in(cx, |workspace, window, cx| {
 8389            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8390        });
 8391        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8392        project.update(cx, |project, cx| {
 8393            assert_eq!(
 8394                project.active_entry(),
 8395                project
 8396                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 8397                    .map(|e| e.id)
 8398            );
 8399        });
 8400
 8401        // Close the active item
 8402        pane.update_in(cx, |pane, window, cx| {
 8403            pane.close_active_item(&Default::default(), window, cx)
 8404        })
 8405        .await
 8406        .unwrap();
 8407        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8408        project.update(cx, |project, cx| {
 8409            assert_eq!(
 8410                project.active_entry(),
 8411                project
 8412                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8413                    .map(|e| e.id)
 8414            );
 8415        });
 8416
 8417        // Add a project folder
 8418        project
 8419            .update(cx, |project, cx| {
 8420                project.find_or_create_worktree("root2", true, cx)
 8421            })
 8422            .await
 8423            .unwrap();
 8424        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8425
 8426        // Remove a project folder
 8427        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8428        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8429    }
 8430
 8431    #[gpui::test]
 8432    async fn test_close_window(cx: &mut TestAppContext) {
 8433        init_test(cx);
 8434
 8435        let fs = FakeFs::new(cx.executor());
 8436        fs.insert_tree("/root", json!({ "one": "" })).await;
 8437
 8438        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8439        let (workspace, cx) =
 8440            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8441
 8442        // When there are no dirty items, there's nothing to do.
 8443        let item1 = cx.new(TestItem::new);
 8444        workspace.update_in(cx, |w, window, cx| {
 8445            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8446        });
 8447        let task = workspace.update_in(cx, |w, window, cx| {
 8448            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8449        });
 8450        assert!(task.await.unwrap());
 8451
 8452        // When there are dirty untitled items, prompt to save each one. If the user
 8453        // cancels any prompt, then abort.
 8454        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8455        let item3 = cx.new(|cx| {
 8456            TestItem::new(cx)
 8457                .with_dirty(true)
 8458                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8459        });
 8460        workspace.update_in(cx, |w, window, cx| {
 8461            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8462            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8463        });
 8464        let task = workspace.update_in(cx, |w, window, cx| {
 8465            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8466        });
 8467        cx.executor().run_until_parked();
 8468        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8469        cx.executor().run_until_parked();
 8470        assert!(!cx.has_pending_prompt());
 8471        assert!(!task.await.unwrap());
 8472    }
 8473
 8474    #[gpui::test]
 8475    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8476        init_test(cx);
 8477
 8478        // Register TestItem as a serializable item
 8479        cx.update(|cx| {
 8480            register_serializable_item::<TestItem>(cx);
 8481        });
 8482
 8483        let fs = FakeFs::new(cx.executor());
 8484        fs.insert_tree("/root", json!({ "one": "" })).await;
 8485
 8486        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8487        let (workspace, cx) =
 8488            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8489
 8490        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8491        let item1 = cx.new(|cx| {
 8492            TestItem::new(cx)
 8493                .with_dirty(true)
 8494                .with_serialize(|| Some(Task::ready(Ok(()))))
 8495        });
 8496        let item2 = cx.new(|cx| {
 8497            TestItem::new(cx)
 8498                .with_dirty(true)
 8499                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8500                .with_serialize(|| Some(Task::ready(Ok(()))))
 8501        });
 8502        workspace.update_in(cx, |w, window, cx| {
 8503            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8504            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8505        });
 8506        let task = workspace.update_in(cx, |w, window, cx| {
 8507            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8508        });
 8509        assert!(task.await.unwrap());
 8510    }
 8511
 8512    #[gpui::test]
 8513    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8514        init_test(cx);
 8515
 8516        let fs = FakeFs::new(cx.executor());
 8517
 8518        let project = Project::test(fs, None, cx).await;
 8519        let (workspace, cx) =
 8520            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8521
 8522        let item1 = cx.new(|cx| {
 8523            TestItem::new(cx)
 8524                .with_dirty(true)
 8525                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8526        });
 8527        let item2 = cx.new(|cx| {
 8528            TestItem::new(cx)
 8529                .with_dirty(true)
 8530                .with_conflict(true)
 8531                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8532        });
 8533        let item3 = cx.new(|cx| {
 8534            TestItem::new(cx)
 8535                .with_dirty(true)
 8536                .with_conflict(true)
 8537                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8538        });
 8539        let item4 = cx.new(|cx| {
 8540            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8541                let project_item = TestProjectItem::new_untitled(cx);
 8542                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8543                project_item
 8544            }])
 8545        });
 8546        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8547            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8548            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8549            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8550            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8551            workspace.active_pane().clone()
 8552        });
 8553
 8554        let close_items = pane.update_in(cx, |pane, window, cx| {
 8555            pane.activate_item(1, true, true, window, cx);
 8556            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8557            let item1_id = item1.item_id();
 8558            let item3_id = item3.item_id();
 8559            let item4_id = item4.item_id();
 8560            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8561                [item1_id, item3_id, item4_id].contains(&id)
 8562            })
 8563        });
 8564        cx.executor().run_until_parked();
 8565
 8566        assert!(cx.has_pending_prompt());
 8567        cx.simulate_prompt_answer("Save all");
 8568
 8569        cx.executor().run_until_parked();
 8570
 8571        // Item 1 is saved. There's a prompt to save item 3.
 8572        pane.update(cx, |pane, cx| {
 8573            assert_eq!(item1.read(cx).save_count, 1);
 8574            assert_eq!(item1.read(cx).save_as_count, 0);
 8575            assert_eq!(item1.read(cx).reload_count, 0);
 8576            assert_eq!(pane.items_len(), 3);
 8577            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8578        });
 8579        assert!(cx.has_pending_prompt());
 8580
 8581        // Cancel saving item 3.
 8582        cx.simulate_prompt_answer("Discard");
 8583        cx.executor().run_until_parked();
 8584
 8585        // Item 3 is reloaded. There's a prompt to save item 4.
 8586        pane.update(cx, |pane, cx| {
 8587            assert_eq!(item3.read(cx).save_count, 0);
 8588            assert_eq!(item3.read(cx).save_as_count, 0);
 8589            assert_eq!(item3.read(cx).reload_count, 1);
 8590            assert_eq!(pane.items_len(), 2);
 8591            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8592        });
 8593
 8594        // There's a prompt for a path for item 4.
 8595        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8596        close_items.await.unwrap();
 8597
 8598        // The requested items are closed.
 8599        pane.update(cx, |pane, cx| {
 8600            assert_eq!(item4.read(cx).save_count, 0);
 8601            assert_eq!(item4.read(cx).save_as_count, 1);
 8602            assert_eq!(item4.read(cx).reload_count, 0);
 8603            assert_eq!(pane.items_len(), 1);
 8604            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8605        });
 8606    }
 8607
 8608    #[gpui::test]
 8609    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8610        init_test(cx);
 8611
 8612        let fs = FakeFs::new(cx.executor());
 8613        let project = Project::test(fs, [], cx).await;
 8614        let (workspace, cx) =
 8615            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8616
 8617        // Create several workspace items with single project entries, and two
 8618        // workspace items with multiple project entries.
 8619        let single_entry_items = (0..=4)
 8620            .map(|project_entry_id| {
 8621                cx.new(|cx| {
 8622                    TestItem::new(cx)
 8623                        .with_dirty(true)
 8624                        .with_project_items(&[dirty_project_item(
 8625                            project_entry_id,
 8626                            &format!("{project_entry_id}.txt"),
 8627                            cx,
 8628                        )])
 8629                })
 8630            })
 8631            .collect::<Vec<_>>();
 8632        let item_2_3 = cx.new(|cx| {
 8633            TestItem::new(cx)
 8634                .with_dirty(true)
 8635                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8636                .with_project_items(&[
 8637                    single_entry_items[2].read(cx).project_items[0].clone(),
 8638                    single_entry_items[3].read(cx).project_items[0].clone(),
 8639                ])
 8640        });
 8641        let item_3_4 = cx.new(|cx| {
 8642            TestItem::new(cx)
 8643                .with_dirty(true)
 8644                .with_buffer_kind(ItemBufferKind::Multibuffer)
 8645                .with_project_items(&[
 8646                    single_entry_items[3].read(cx).project_items[0].clone(),
 8647                    single_entry_items[4].read(cx).project_items[0].clone(),
 8648                ])
 8649        });
 8650
 8651        // Create two panes that contain the following project entries:
 8652        //   left pane:
 8653        //     multi-entry items:   (2, 3)
 8654        //     single-entry items:  0, 2, 3, 4
 8655        //   right pane:
 8656        //     single-entry items:  4, 1
 8657        //     multi-entry items:   (3, 4)
 8658        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8659            let left_pane = workspace.active_pane().clone();
 8660            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8661            workspace.add_item_to_active_pane(
 8662                single_entry_items[0].boxed_clone(),
 8663                None,
 8664                true,
 8665                window,
 8666                cx,
 8667            );
 8668            workspace.add_item_to_active_pane(
 8669                single_entry_items[2].boxed_clone(),
 8670                None,
 8671                true,
 8672                window,
 8673                cx,
 8674            );
 8675            workspace.add_item_to_active_pane(
 8676                single_entry_items[3].boxed_clone(),
 8677                None,
 8678                true,
 8679                window,
 8680                cx,
 8681            );
 8682            workspace.add_item_to_active_pane(
 8683                single_entry_items[4].boxed_clone(),
 8684                None,
 8685                true,
 8686                window,
 8687                cx,
 8688            );
 8689
 8690            let right_pane = workspace
 8691                .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
 8692                .unwrap();
 8693
 8694            right_pane.update(cx, |pane, cx| {
 8695                pane.add_item(
 8696                    single_entry_items[1].boxed_clone(),
 8697                    true,
 8698                    true,
 8699                    None,
 8700                    window,
 8701                    cx,
 8702                );
 8703                pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8704            });
 8705
 8706            (left_pane, right_pane)
 8707        });
 8708
 8709        cx.focus(&right_pane);
 8710
 8711        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8712            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8713                .unwrap()
 8714        });
 8715        cx.executor().run_until_parked();
 8716
 8717        let msg = cx.pending_prompt().unwrap().0;
 8718        assert!(msg.contains("1.txt"));
 8719        assert!(!msg.contains("2.txt"));
 8720        assert!(!msg.contains("3.txt"));
 8721        assert!(!msg.contains("4.txt"));
 8722
 8723        cx.simulate_prompt_answer("Cancel");
 8724        close.await;
 8725
 8726        left_pane
 8727            .update_in(cx, |left_pane, window, cx| {
 8728                left_pane.close_item_by_id(
 8729                    single_entry_items[3].entity_id(),
 8730                    SaveIntent::Skip,
 8731                    window,
 8732                    cx,
 8733                )
 8734            })
 8735            .await
 8736            .unwrap();
 8737
 8738        close = right_pane.update_in(cx, |pane, window, cx| {
 8739            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8740                .unwrap()
 8741        });
 8742        cx.executor().run_until_parked();
 8743
 8744        let details = cx.pending_prompt().unwrap().1;
 8745        assert!(details.contains("1.txt"));
 8746        assert!(!details.contains("2.txt"));
 8747        assert!(details.contains("3.txt"));
 8748        // ideally this assertion could be made, but today we can only
 8749        // save whole items not project items, so the orphaned item 3 causes
 8750        // 4 to be saved too.
 8751        // assert!(!details.contains("4.txt"));
 8752
 8753        cx.simulate_prompt_answer("Save all");
 8754
 8755        cx.executor().run_until_parked();
 8756        close.await;
 8757        right_pane.read_with(cx, |pane, _| {
 8758            assert_eq!(pane.items_len(), 0);
 8759        });
 8760    }
 8761
 8762    #[gpui::test]
 8763    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8764        init_test(cx);
 8765
 8766        let fs = FakeFs::new(cx.executor());
 8767        let project = Project::test(fs, [], cx).await;
 8768        let (workspace, cx) =
 8769            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8770        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8771
 8772        let item = cx.new(|cx| {
 8773            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8774        });
 8775        let item_id = item.entity_id();
 8776        workspace.update_in(cx, |workspace, window, cx| {
 8777            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8778        });
 8779
 8780        // Autosave on window change.
 8781        item.update(cx, |item, cx| {
 8782            SettingsStore::update_global(cx, |settings, cx| {
 8783                settings.update_user_settings(cx, |settings| {
 8784                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 8785                })
 8786            });
 8787            item.is_dirty = true;
 8788        });
 8789
 8790        // Deactivating the window saves the file.
 8791        cx.deactivate_window();
 8792        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8793
 8794        // Re-activating the window doesn't save the file.
 8795        cx.update(|window, _| window.activate_window());
 8796        cx.executor().run_until_parked();
 8797        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8798
 8799        // Autosave on focus change.
 8800        item.update_in(cx, |item, window, cx| {
 8801            cx.focus_self(window);
 8802            SettingsStore::update_global(cx, |settings, cx| {
 8803                settings.update_user_settings(cx, |settings| {
 8804                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 8805                })
 8806            });
 8807            item.is_dirty = true;
 8808        });
 8809        // Blurring the item saves the file.
 8810        item.update_in(cx, |_, window, _| window.blur());
 8811        cx.executor().run_until_parked();
 8812        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8813
 8814        // Deactivating the window still saves the file.
 8815        item.update_in(cx, |item, window, cx| {
 8816            cx.focus_self(window);
 8817            item.is_dirty = true;
 8818        });
 8819        cx.deactivate_window();
 8820        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8821
 8822        // Autosave after delay.
 8823        item.update(cx, |item, cx| {
 8824            SettingsStore::update_global(cx, |settings, cx| {
 8825                settings.update_user_settings(cx, |settings| {
 8826                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 8827                        milliseconds: 500.into(),
 8828                    });
 8829                })
 8830            });
 8831            item.is_dirty = true;
 8832            cx.emit(ItemEvent::Edit);
 8833        });
 8834
 8835        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8836        cx.executor().advance_clock(Duration::from_millis(250));
 8837        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8838
 8839        // After delay expires, the file is saved.
 8840        cx.executor().advance_clock(Duration::from_millis(250));
 8841        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8842
 8843        // Autosave after delay, should save earlier than delay if tab is closed
 8844        item.update(cx, |item, cx| {
 8845            item.is_dirty = true;
 8846            cx.emit(ItemEvent::Edit);
 8847        });
 8848        cx.executor().advance_clock(Duration::from_millis(250));
 8849        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8850
 8851        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 8852        pane.update_in(cx, |pane, window, cx| {
 8853            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8854        })
 8855        .await
 8856        .unwrap();
 8857        assert!(!cx.has_pending_prompt());
 8858        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8859
 8860        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8861        workspace.update_in(cx, |workspace, window, cx| {
 8862            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8863        });
 8864        item.update_in(cx, |item, _window, cx| {
 8865            item.is_dirty = true;
 8866            for project_item in &mut item.project_items {
 8867                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8868            }
 8869        });
 8870        cx.run_until_parked();
 8871        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8872
 8873        // Autosave on focus change, ensuring closing the tab counts as such.
 8874        item.update(cx, |item, cx| {
 8875            SettingsStore::update_global(cx, |settings, cx| {
 8876                settings.update_user_settings(cx, |settings| {
 8877                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 8878                })
 8879            });
 8880            item.is_dirty = true;
 8881            for project_item in &mut item.project_items {
 8882                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8883            }
 8884        });
 8885
 8886        pane.update_in(cx, |pane, window, cx| {
 8887            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8888        })
 8889        .await
 8890        .unwrap();
 8891        assert!(!cx.has_pending_prompt());
 8892        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8893
 8894        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8895        workspace.update_in(cx, |workspace, window, cx| {
 8896            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8897        });
 8898        item.update_in(cx, |item, window, cx| {
 8899            item.project_items[0].update(cx, |item, _| {
 8900                item.entry_id = None;
 8901            });
 8902            item.is_dirty = true;
 8903            window.blur();
 8904        });
 8905        cx.run_until_parked();
 8906        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8907
 8908        // Ensure autosave is prevented for deleted files also when closing the buffer.
 8909        let _close_items = pane.update_in(cx, |pane, window, cx| {
 8910            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8911        });
 8912        cx.run_until_parked();
 8913        assert!(cx.has_pending_prompt());
 8914        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 8915    }
 8916
 8917    #[gpui::test]
 8918    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 8919        init_test(cx);
 8920
 8921        let fs = FakeFs::new(cx.executor());
 8922
 8923        let project = Project::test(fs, [], cx).await;
 8924        let (workspace, cx) =
 8925            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8926
 8927        let item = cx.new(|cx| {
 8928            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8929        });
 8930        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8931        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 8932        let toolbar_notify_count = Rc::new(RefCell::new(0));
 8933
 8934        workspace.update_in(cx, |workspace, window, cx| {
 8935            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8936            let toolbar_notification_count = toolbar_notify_count.clone();
 8937            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 8938                *toolbar_notification_count.borrow_mut() += 1
 8939            })
 8940            .detach();
 8941        });
 8942
 8943        pane.read_with(cx, |pane, _| {
 8944            assert!(!pane.can_navigate_backward());
 8945            assert!(!pane.can_navigate_forward());
 8946        });
 8947
 8948        item.update_in(cx, |item, _, cx| {
 8949            item.set_state("one".to_string(), cx);
 8950        });
 8951
 8952        // Toolbar must be notified to re-render the navigation buttons
 8953        assert_eq!(*toolbar_notify_count.borrow(), 1);
 8954
 8955        pane.read_with(cx, |pane, _| {
 8956            assert!(pane.can_navigate_backward());
 8957            assert!(!pane.can_navigate_forward());
 8958        });
 8959
 8960        workspace
 8961            .update_in(cx, |workspace, window, cx| {
 8962                workspace.go_back(pane.downgrade(), window, cx)
 8963            })
 8964            .await
 8965            .unwrap();
 8966
 8967        assert_eq!(*toolbar_notify_count.borrow(), 2);
 8968        pane.read_with(cx, |pane, _| {
 8969            assert!(!pane.can_navigate_backward());
 8970            assert!(pane.can_navigate_forward());
 8971        });
 8972    }
 8973
 8974    #[gpui::test]
 8975    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 8976        init_test(cx);
 8977        let fs = FakeFs::new(cx.executor());
 8978
 8979        let project = Project::test(fs, [], cx).await;
 8980        let (workspace, cx) =
 8981            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8982
 8983        let panel = workspace.update_in(cx, |workspace, window, cx| {
 8984            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 8985            workspace.add_panel(panel.clone(), window, cx);
 8986
 8987            workspace
 8988                .right_dock()
 8989                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 8990
 8991            panel
 8992        });
 8993
 8994        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8995        pane.update_in(cx, |pane, window, cx| {
 8996            let item = cx.new(TestItem::new);
 8997            pane.add_item(Box::new(item), true, true, None, window, cx);
 8998        });
 8999
 9000        // Transfer focus from center to panel
 9001        workspace.update_in(cx, |workspace, window, cx| {
 9002            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9003        });
 9004
 9005        workspace.update_in(cx, |workspace, window, cx| {
 9006            assert!(workspace.right_dock().read(cx).is_open());
 9007            assert!(!panel.is_zoomed(window, cx));
 9008            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9009        });
 9010
 9011        // Transfer focus from panel to center
 9012        workspace.update_in(cx, |workspace, window, cx| {
 9013            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9014        });
 9015
 9016        workspace.update_in(cx, |workspace, window, cx| {
 9017            assert!(workspace.right_dock().read(cx).is_open());
 9018            assert!(!panel.is_zoomed(window, cx));
 9019            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9020        });
 9021
 9022        // Close the dock
 9023        workspace.update_in(cx, |workspace, window, cx| {
 9024            workspace.toggle_dock(DockPosition::Right, window, cx);
 9025        });
 9026
 9027        workspace.update_in(cx, |workspace, window, cx| {
 9028            assert!(!workspace.right_dock().read(cx).is_open());
 9029            assert!(!panel.is_zoomed(window, cx));
 9030            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9031        });
 9032
 9033        // Open the dock
 9034        workspace.update_in(cx, |workspace, window, cx| {
 9035            workspace.toggle_dock(DockPosition::Right, window, cx);
 9036        });
 9037
 9038        workspace.update_in(cx, |workspace, window, cx| {
 9039            assert!(workspace.right_dock().read(cx).is_open());
 9040            assert!(!panel.is_zoomed(window, cx));
 9041            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9042        });
 9043
 9044        // Focus and zoom panel
 9045        panel.update_in(cx, |panel, window, cx| {
 9046            cx.focus_self(window);
 9047            panel.set_zoomed(true, window, cx)
 9048        });
 9049
 9050        workspace.update_in(cx, |workspace, window, cx| {
 9051            assert!(workspace.right_dock().read(cx).is_open());
 9052            assert!(panel.is_zoomed(window, cx));
 9053            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9054        });
 9055
 9056        // Transfer focus to the center closes the dock
 9057        workspace.update_in(cx, |workspace, window, cx| {
 9058            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9059        });
 9060
 9061        workspace.update_in(cx, |workspace, window, cx| {
 9062            assert!(!workspace.right_dock().read(cx).is_open());
 9063            assert!(panel.is_zoomed(window, cx));
 9064            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9065        });
 9066
 9067        // Transferring focus back to the panel keeps it zoomed
 9068        workspace.update_in(cx, |workspace, window, cx| {
 9069            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9070        });
 9071
 9072        workspace.update_in(cx, |workspace, window, cx| {
 9073            assert!(workspace.right_dock().read(cx).is_open());
 9074            assert!(panel.is_zoomed(window, cx));
 9075            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9076        });
 9077
 9078        // Close the dock while it is zoomed
 9079        workspace.update_in(cx, |workspace, window, cx| {
 9080            workspace.toggle_dock(DockPosition::Right, window, cx)
 9081        });
 9082
 9083        workspace.update_in(cx, |workspace, window, cx| {
 9084            assert!(!workspace.right_dock().read(cx).is_open());
 9085            assert!(panel.is_zoomed(window, cx));
 9086            assert!(workspace.zoomed.is_none());
 9087            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9088        });
 9089
 9090        // Opening the dock, when it's zoomed, retains focus
 9091        workspace.update_in(cx, |workspace, window, cx| {
 9092            workspace.toggle_dock(DockPosition::Right, window, cx)
 9093        });
 9094
 9095        workspace.update_in(cx, |workspace, window, cx| {
 9096            assert!(workspace.right_dock().read(cx).is_open());
 9097            assert!(panel.is_zoomed(window, cx));
 9098            assert!(workspace.zoomed.is_some());
 9099            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9100        });
 9101
 9102        // Unzoom and close the panel, zoom the active pane.
 9103        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9104        workspace.update_in(cx, |workspace, window, cx| {
 9105            workspace.toggle_dock(DockPosition::Right, window, cx)
 9106        });
 9107        pane.update_in(cx, |pane, window, cx| {
 9108            pane.toggle_zoom(&Default::default(), window, cx)
 9109        });
 9110
 9111        // Opening a dock unzooms the pane.
 9112        workspace.update_in(cx, |workspace, window, cx| {
 9113            workspace.toggle_dock(DockPosition::Right, window, cx)
 9114        });
 9115        workspace.update_in(cx, |workspace, window, cx| {
 9116            let pane = pane.read(cx);
 9117            assert!(!pane.is_zoomed());
 9118            assert!(!pane.focus_handle(cx).is_focused(window));
 9119            assert!(workspace.right_dock().read(cx).is_open());
 9120            assert!(workspace.zoomed.is_none());
 9121        });
 9122    }
 9123
 9124    #[gpui::test]
 9125    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 9126        init_test(cx);
 9127
 9128        let fs = FakeFs::new(cx.executor());
 9129
 9130        let project = Project::test(fs, None, cx).await;
 9131        let (workspace, cx) =
 9132            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9133
 9134        // Let's arrange the panes like this:
 9135        //
 9136        // +-----------------------+
 9137        // |         top           |
 9138        // +------+--------+-------+
 9139        // | left | center | right |
 9140        // +------+--------+-------+
 9141        // |        bottom         |
 9142        // +-----------------------+
 9143
 9144        let top_item = cx.new(|cx| {
 9145            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 9146        });
 9147        let bottom_item = cx.new(|cx| {
 9148            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 9149        });
 9150        let left_item = cx.new(|cx| {
 9151            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 9152        });
 9153        let right_item = cx.new(|cx| {
 9154            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 9155        });
 9156        let center_item = cx.new(|cx| {
 9157            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 9158        });
 9159
 9160        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9161            let top_pane_id = workspace.active_pane().entity_id();
 9162            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 9163            workspace.split_pane(
 9164                workspace.active_pane().clone(),
 9165                SplitDirection::Down,
 9166                window,
 9167                cx,
 9168            );
 9169            top_pane_id
 9170        });
 9171        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9172            let bottom_pane_id = workspace.active_pane().entity_id();
 9173            workspace.add_item_to_active_pane(
 9174                Box::new(bottom_item.clone()),
 9175                None,
 9176                false,
 9177                window,
 9178                cx,
 9179            );
 9180            workspace.split_pane(
 9181                workspace.active_pane().clone(),
 9182                SplitDirection::Up,
 9183                window,
 9184                cx,
 9185            );
 9186            bottom_pane_id
 9187        });
 9188        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9189            let left_pane_id = workspace.active_pane().entity_id();
 9190            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 9191            workspace.split_pane(
 9192                workspace.active_pane().clone(),
 9193                SplitDirection::Right,
 9194                window,
 9195                cx,
 9196            );
 9197            left_pane_id
 9198        });
 9199        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9200            let right_pane_id = workspace.active_pane().entity_id();
 9201            workspace.add_item_to_active_pane(
 9202                Box::new(right_item.clone()),
 9203                None,
 9204                false,
 9205                window,
 9206                cx,
 9207            );
 9208            workspace.split_pane(
 9209                workspace.active_pane().clone(),
 9210                SplitDirection::Left,
 9211                window,
 9212                cx,
 9213            );
 9214            right_pane_id
 9215        });
 9216        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9217            let center_pane_id = workspace.active_pane().entity_id();
 9218            workspace.add_item_to_active_pane(
 9219                Box::new(center_item.clone()),
 9220                None,
 9221                false,
 9222                window,
 9223                cx,
 9224            );
 9225            center_pane_id
 9226        });
 9227        cx.executor().run_until_parked();
 9228
 9229        workspace.update_in(cx, |workspace, window, cx| {
 9230            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9231
 9232            // Join into next from center pane into right
 9233            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9234        });
 9235
 9236        workspace.update_in(cx, |workspace, window, cx| {
 9237            let active_pane = workspace.active_pane();
 9238            assert_eq!(right_pane_id, active_pane.entity_id());
 9239            assert_eq!(2, active_pane.read(cx).items_len());
 9240            let item_ids_in_pane =
 9241                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9242            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9243            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9244
 9245            // Join into next from right pane into bottom
 9246            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9247        });
 9248
 9249        workspace.update_in(cx, |workspace, window, cx| {
 9250            let active_pane = workspace.active_pane();
 9251            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9252            assert_eq!(3, active_pane.read(cx).items_len());
 9253            let item_ids_in_pane =
 9254                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9255            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9256            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9257            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9258
 9259            // Join into next from bottom pane into left
 9260            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9261        });
 9262
 9263        workspace.update_in(cx, |workspace, window, cx| {
 9264            let active_pane = workspace.active_pane();
 9265            assert_eq!(left_pane_id, active_pane.entity_id());
 9266            assert_eq!(4, active_pane.read(cx).items_len());
 9267            let item_ids_in_pane =
 9268                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9269            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9270            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9271            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9272            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9273
 9274            // Join into next from left pane into top
 9275            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9276        });
 9277
 9278        workspace.update_in(cx, |workspace, window, cx| {
 9279            let active_pane = workspace.active_pane();
 9280            assert_eq!(top_pane_id, active_pane.entity_id());
 9281            assert_eq!(5, active_pane.read(cx).items_len());
 9282            let item_ids_in_pane =
 9283                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9284            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9285            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9286            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9287            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9288            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9289
 9290            // Single pane left: no-op
 9291            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9292        });
 9293
 9294        workspace.update(cx, |workspace, _cx| {
 9295            let active_pane = workspace.active_pane();
 9296            assert_eq!(top_pane_id, active_pane.entity_id());
 9297        });
 9298    }
 9299
 9300    fn add_an_item_to_active_pane(
 9301        cx: &mut VisualTestContext,
 9302        workspace: &Entity<Workspace>,
 9303        item_id: u64,
 9304    ) -> Entity<TestItem> {
 9305        let item = cx.new(|cx| {
 9306            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9307                item_id,
 9308                "item{item_id}.txt",
 9309                cx,
 9310            )])
 9311        });
 9312        workspace.update_in(cx, |workspace, window, cx| {
 9313            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9314        });
 9315        item
 9316    }
 9317
 9318    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9319        workspace.update_in(cx, |workspace, window, cx| {
 9320            workspace.split_pane(
 9321                workspace.active_pane().clone(),
 9322                SplitDirection::Right,
 9323                window,
 9324                cx,
 9325            )
 9326        })
 9327    }
 9328
 9329    #[gpui::test]
 9330    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9331        init_test(cx);
 9332        let fs = FakeFs::new(cx.executor());
 9333        let project = Project::test(fs, None, cx).await;
 9334        let (workspace, cx) =
 9335            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9336
 9337        add_an_item_to_active_pane(cx, &workspace, 1);
 9338        split_pane(cx, &workspace);
 9339        add_an_item_to_active_pane(cx, &workspace, 2);
 9340        split_pane(cx, &workspace); // empty pane
 9341        split_pane(cx, &workspace);
 9342        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9343
 9344        cx.executor().run_until_parked();
 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, 4);
 9356            assert_eq!(num_items_in_current_pane, 1);
 9357            assert_eq!(active_item.item_id(), last_item.item_id());
 9358        });
 9359
 9360        workspace.update_in(cx, |workspace, window, cx| {
 9361            workspace.join_all_panes(window, cx);
 9362        });
 9363
 9364        workspace.update(cx, |workspace, cx| {
 9365            let num_panes = workspace.panes().len();
 9366            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9367            let active_item = workspace
 9368                .active_pane()
 9369                .read(cx)
 9370                .active_item()
 9371                .expect("item is in focus");
 9372
 9373            assert_eq!(num_panes, 1);
 9374            assert_eq!(num_items_in_current_pane, 3);
 9375            assert_eq!(active_item.item_id(), last_item.item_id());
 9376        });
 9377    }
 9378    struct TestModal(FocusHandle);
 9379
 9380    impl TestModal {
 9381        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9382            Self(cx.focus_handle())
 9383        }
 9384    }
 9385
 9386    impl EventEmitter<DismissEvent> for TestModal {}
 9387
 9388    impl Focusable for TestModal {
 9389        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9390            self.0.clone()
 9391        }
 9392    }
 9393
 9394    impl ModalView for TestModal {}
 9395
 9396    impl Render for TestModal {
 9397        fn render(
 9398            &mut self,
 9399            _window: &mut Window,
 9400            _cx: &mut Context<TestModal>,
 9401        ) -> impl IntoElement {
 9402            div().track_focus(&self.0)
 9403        }
 9404    }
 9405
 9406    #[gpui::test]
 9407    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9408        init_test(cx);
 9409        let fs = FakeFs::new(cx.executor());
 9410
 9411        let project = Project::test(fs, [], cx).await;
 9412        let (workspace, cx) =
 9413            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9414
 9415        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9416            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9417            workspace.add_panel(panel_1.clone(), window, cx);
 9418            workspace.toggle_dock(DockPosition::Left, window, cx);
 9419            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9420            workspace.add_panel(panel_2.clone(), window, cx);
 9421            workspace.toggle_dock(DockPosition::Right, window, cx);
 9422
 9423            let left_dock = workspace.left_dock();
 9424            assert_eq!(
 9425                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9426                panel_1.panel_id()
 9427            );
 9428            assert_eq!(
 9429                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9430                panel_1.size(window, cx)
 9431            );
 9432
 9433            left_dock.update(cx, |left_dock, cx| {
 9434                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9435            });
 9436            assert_eq!(
 9437                workspace
 9438                    .right_dock()
 9439                    .read(cx)
 9440                    .visible_panel()
 9441                    .unwrap()
 9442                    .panel_id(),
 9443                panel_2.panel_id(),
 9444            );
 9445
 9446            (panel_1, panel_2)
 9447        });
 9448
 9449        // Move panel_1 to the right
 9450        panel_1.update_in(cx, |panel_1, window, cx| {
 9451            panel_1.set_position(DockPosition::Right, window, cx)
 9452        });
 9453
 9454        workspace.update_in(cx, |workspace, window, cx| {
 9455            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9456            // Since it was the only panel on the left, the left dock should now be closed.
 9457            assert!(!workspace.left_dock().read(cx).is_open());
 9458            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9459            let right_dock = workspace.right_dock();
 9460            assert_eq!(
 9461                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9462                panel_1.panel_id()
 9463            );
 9464            assert_eq!(
 9465                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9466                px(1337.)
 9467            );
 9468
 9469            // Now we move panel_2 to the left
 9470            panel_2.set_position(DockPosition::Left, window, cx);
 9471        });
 9472
 9473        workspace.update(cx, |workspace, cx| {
 9474            // Since panel_2 was not visible on the right, we don't open the left dock.
 9475            assert!(!workspace.left_dock().read(cx).is_open());
 9476            // And the right dock is unaffected in its displaying of panel_1
 9477            assert!(workspace.right_dock().read(cx).is_open());
 9478            assert_eq!(
 9479                workspace
 9480                    .right_dock()
 9481                    .read(cx)
 9482                    .visible_panel()
 9483                    .unwrap()
 9484                    .panel_id(),
 9485                panel_1.panel_id(),
 9486            );
 9487        });
 9488
 9489        // Move panel_1 back to the left
 9490        panel_1.update_in(cx, |panel_1, window, cx| {
 9491            panel_1.set_position(DockPosition::Left, window, cx)
 9492        });
 9493
 9494        workspace.update_in(cx, |workspace, window, cx| {
 9495            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9496            let left_dock = workspace.left_dock();
 9497            assert!(left_dock.read(cx).is_open());
 9498            assert_eq!(
 9499                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9500                panel_1.panel_id()
 9501            );
 9502            assert_eq!(
 9503                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9504                px(1337.)
 9505            );
 9506            // And the right dock should be closed as it no longer has any panels.
 9507            assert!(!workspace.right_dock().read(cx).is_open());
 9508
 9509            // Now we move panel_1 to the bottom
 9510            panel_1.set_position(DockPosition::Bottom, window, cx);
 9511        });
 9512
 9513        workspace.update_in(cx, |workspace, window, cx| {
 9514            // Since panel_1 was visible on the left, we close the left dock.
 9515            assert!(!workspace.left_dock().read(cx).is_open());
 9516            // The bottom dock is sized based on the panel's default size,
 9517            // since the panel orientation changed from vertical to horizontal.
 9518            let bottom_dock = workspace.bottom_dock();
 9519            assert_eq!(
 9520                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9521                panel_1.size(window, cx),
 9522            );
 9523            // Close bottom dock and move panel_1 back to the left.
 9524            bottom_dock.update(cx, |bottom_dock, cx| {
 9525                bottom_dock.set_open(false, window, cx)
 9526            });
 9527            panel_1.set_position(DockPosition::Left, window, cx);
 9528        });
 9529
 9530        // Emit activated event on panel 1
 9531        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9532
 9533        // Now the left dock is open and panel_1 is active and focused.
 9534        workspace.update_in(cx, |workspace, window, cx| {
 9535            let left_dock = workspace.left_dock();
 9536            assert!(left_dock.read(cx).is_open());
 9537            assert_eq!(
 9538                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9539                panel_1.panel_id(),
 9540            );
 9541            assert!(panel_1.focus_handle(cx).is_focused(window));
 9542        });
 9543
 9544        // Emit closed event on panel 2, which is not active
 9545        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9546
 9547        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9548        workspace.update(cx, |workspace, cx| {
 9549            let left_dock = workspace.left_dock();
 9550            assert!(left_dock.read(cx).is_open());
 9551            assert_eq!(
 9552                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9553                panel_1.panel_id(),
 9554            );
 9555        });
 9556
 9557        // Emitting a ZoomIn event shows the panel as zoomed.
 9558        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9559        workspace.read_with(cx, |workspace, _| {
 9560            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9561            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9562        });
 9563
 9564        // Move panel to another dock while it is zoomed
 9565        panel_1.update_in(cx, |panel, window, cx| {
 9566            panel.set_position(DockPosition::Right, window, cx)
 9567        });
 9568        workspace.read_with(cx, |workspace, _| {
 9569            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9570
 9571            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9572        });
 9573
 9574        // This is a helper for getting a:
 9575        // - valid focus on an element,
 9576        // - that isn't a part of the panes and panels system of the Workspace,
 9577        // - and doesn't trigger the 'on_focus_lost' API.
 9578        let focus_other_view = {
 9579            let workspace = workspace.clone();
 9580            move |cx: &mut VisualTestContext| {
 9581                workspace.update_in(cx, |workspace, window, cx| {
 9582                    if workspace.active_modal::<TestModal>(cx).is_some() {
 9583                        workspace.toggle_modal(window, cx, TestModal::new);
 9584                        workspace.toggle_modal(window, cx, TestModal::new);
 9585                    } else {
 9586                        workspace.toggle_modal(window, cx, TestModal::new);
 9587                    }
 9588                })
 9589            }
 9590        };
 9591
 9592        // If focus is transferred to another view that's not a panel or another pane, we still show
 9593        // the panel as zoomed.
 9594        focus_other_view(cx);
 9595        workspace.read_with(cx, |workspace, _| {
 9596            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9597            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9598        });
 9599
 9600        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9601        workspace.update_in(cx, |_workspace, window, cx| {
 9602            cx.focus_self(window);
 9603        });
 9604        workspace.read_with(cx, |workspace, _| {
 9605            assert_eq!(workspace.zoomed, None);
 9606            assert_eq!(workspace.zoomed_position, None);
 9607        });
 9608
 9609        // If focus is transferred again to another view that's not a panel or a pane, we won't
 9610        // show the panel as zoomed because it wasn't zoomed before.
 9611        focus_other_view(cx);
 9612        workspace.read_with(cx, |workspace, _| {
 9613            assert_eq!(workspace.zoomed, None);
 9614            assert_eq!(workspace.zoomed_position, None);
 9615        });
 9616
 9617        // When the panel is activated, it is zoomed again.
 9618        cx.dispatch_action(ToggleRightDock);
 9619        workspace.read_with(cx, |workspace, _| {
 9620            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9621            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9622        });
 9623
 9624        // Emitting a ZoomOut event unzooms the panel.
 9625        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
 9626        workspace.read_with(cx, |workspace, _| {
 9627            assert_eq!(workspace.zoomed, None);
 9628            assert_eq!(workspace.zoomed_position, None);
 9629        });
 9630
 9631        // Emit closed event on panel 1, which is active
 9632        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9633
 9634        // Now the left dock is closed, because panel_1 was the active panel
 9635        workspace.update(cx, |workspace, cx| {
 9636            let right_dock = workspace.right_dock();
 9637            assert!(!right_dock.read(cx).is_open());
 9638        });
 9639    }
 9640
 9641    #[gpui::test]
 9642    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
 9643        init_test(cx);
 9644
 9645        let fs = FakeFs::new(cx.background_executor.clone());
 9646        let project = Project::test(fs, [], cx).await;
 9647        let (workspace, cx) =
 9648            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9649        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9650
 9651        let dirty_regular_buffer = cx.new(|cx| {
 9652            TestItem::new(cx)
 9653                .with_dirty(true)
 9654                .with_label("1.txt")
 9655                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9656        });
 9657        let dirty_regular_buffer_2 = cx.new(|cx| {
 9658            TestItem::new(cx)
 9659                .with_dirty(true)
 9660                .with_label("2.txt")
 9661                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9662        });
 9663        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9664            TestItem::new(cx)
 9665                .with_dirty(true)
 9666                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9667                .with_label("Fake Project Search")
 9668                .with_project_items(&[
 9669                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9670                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9671                ])
 9672        });
 9673        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9674        workspace.update_in(cx, |workspace, window, cx| {
 9675            workspace.add_item(
 9676                pane.clone(),
 9677                Box::new(dirty_regular_buffer.clone()),
 9678                None,
 9679                false,
 9680                false,
 9681                window,
 9682                cx,
 9683            );
 9684            workspace.add_item(
 9685                pane.clone(),
 9686                Box::new(dirty_regular_buffer_2.clone()),
 9687                None,
 9688                false,
 9689                false,
 9690                window,
 9691                cx,
 9692            );
 9693            workspace.add_item(
 9694                pane.clone(),
 9695                Box::new(dirty_multi_buffer_with_both.clone()),
 9696                None,
 9697                false,
 9698                false,
 9699                window,
 9700                cx,
 9701            );
 9702        });
 9703
 9704        pane.update_in(cx, |pane, window, cx| {
 9705            pane.activate_item(2, true, true, window, cx);
 9706            assert_eq!(
 9707                pane.active_item().unwrap().item_id(),
 9708                multi_buffer_with_both_files_id,
 9709                "Should select the multi buffer in the pane"
 9710            );
 9711        });
 9712        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9713            pane.close_other_items(
 9714                &CloseOtherItems {
 9715                    save_intent: Some(SaveIntent::Save),
 9716                    close_pinned: true,
 9717                },
 9718                None,
 9719                window,
 9720                cx,
 9721            )
 9722        });
 9723        cx.background_executor.run_until_parked();
 9724        assert!(!cx.has_pending_prompt());
 9725        close_all_but_multi_buffer_task
 9726            .await
 9727            .expect("Closing all buffers but the multi buffer failed");
 9728        pane.update(cx, |pane, cx| {
 9729            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9730            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9731            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9732            assert_eq!(pane.items_len(), 1);
 9733            assert_eq!(
 9734                pane.active_item().unwrap().item_id(),
 9735                multi_buffer_with_both_files_id,
 9736                "Should have only the multi buffer left in the pane"
 9737            );
 9738            assert!(
 9739                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9740                "The multi buffer containing the unsaved buffer should still be dirty"
 9741            );
 9742        });
 9743
 9744        dirty_regular_buffer.update(cx, |buffer, cx| {
 9745            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9746        });
 9747
 9748        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9749            pane.close_active_item(
 9750                &CloseActiveItem {
 9751                    save_intent: Some(SaveIntent::Close),
 9752                    close_pinned: false,
 9753                },
 9754                window,
 9755                cx,
 9756            )
 9757        });
 9758        cx.background_executor.run_until_parked();
 9759        assert!(
 9760            cx.has_pending_prompt(),
 9761            "Dirty multi buffer should prompt a save dialog"
 9762        );
 9763        cx.simulate_prompt_answer("Save");
 9764        cx.background_executor.run_until_parked();
 9765        close_multi_buffer_task
 9766            .await
 9767            .expect("Closing the multi buffer failed");
 9768        pane.update(cx, |pane, cx| {
 9769            assert_eq!(
 9770                dirty_multi_buffer_with_both.read(cx).save_count,
 9771                1,
 9772                "Multi buffer item should get be saved"
 9773            );
 9774            // Test impl does not save inner items, so we do not assert them
 9775            assert_eq!(
 9776                pane.items_len(),
 9777                0,
 9778                "No more items should be left in the pane"
 9779            );
 9780            assert!(pane.active_item().is_none());
 9781        });
 9782    }
 9783
 9784    #[gpui::test]
 9785    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9786        cx: &mut TestAppContext,
 9787    ) {
 9788        init_test(cx);
 9789
 9790        let fs = FakeFs::new(cx.background_executor.clone());
 9791        let project = Project::test(fs, [], cx).await;
 9792        let (workspace, cx) =
 9793            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9794        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9795
 9796        let dirty_regular_buffer = cx.new(|cx| {
 9797            TestItem::new(cx)
 9798                .with_dirty(true)
 9799                .with_label("1.txt")
 9800                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9801        });
 9802        let dirty_regular_buffer_2 = cx.new(|cx| {
 9803            TestItem::new(cx)
 9804                .with_dirty(true)
 9805                .with_label("2.txt")
 9806                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9807        });
 9808        let clear_regular_buffer = cx.new(|cx| {
 9809            TestItem::new(cx)
 9810                .with_label("3.txt")
 9811                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9812        });
 9813
 9814        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9815            TestItem::new(cx)
 9816                .with_dirty(true)
 9817                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9818                .with_label("Fake Project Search")
 9819                .with_project_items(&[
 9820                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9821                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9822                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9823                ])
 9824        });
 9825        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9826        workspace.update_in(cx, |workspace, window, cx| {
 9827            workspace.add_item(
 9828                pane.clone(),
 9829                Box::new(dirty_regular_buffer.clone()),
 9830                None,
 9831                false,
 9832                false,
 9833                window,
 9834                cx,
 9835            );
 9836            workspace.add_item(
 9837                pane.clone(),
 9838                Box::new(dirty_multi_buffer_with_both.clone()),
 9839                None,
 9840                false,
 9841                false,
 9842                window,
 9843                cx,
 9844            );
 9845        });
 9846
 9847        pane.update_in(cx, |pane, window, cx| {
 9848            pane.activate_item(1, true, true, window, cx);
 9849            assert_eq!(
 9850                pane.active_item().unwrap().item_id(),
 9851                multi_buffer_with_both_files_id,
 9852                "Should select the multi buffer in the pane"
 9853            );
 9854        });
 9855        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9856            pane.close_active_item(
 9857                &CloseActiveItem {
 9858                    save_intent: None,
 9859                    close_pinned: false,
 9860                },
 9861                window,
 9862                cx,
 9863            )
 9864        });
 9865        cx.background_executor.run_until_parked();
 9866        assert!(
 9867            cx.has_pending_prompt(),
 9868            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9869        );
 9870    }
 9871
 9872    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9873    /// closed when they are deleted from disk.
 9874    #[gpui::test]
 9875    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9876        init_test(cx);
 9877
 9878        // Enable the close_on_disk_deletion setting
 9879        cx.update_global(|store: &mut SettingsStore, cx| {
 9880            store.update_user_settings(cx, |settings| {
 9881                settings.workspace.close_on_file_delete = Some(true);
 9882            });
 9883        });
 9884
 9885        let fs = FakeFs::new(cx.background_executor.clone());
 9886        let project = Project::test(fs, [], cx).await;
 9887        let (workspace, cx) =
 9888            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9889        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9890
 9891        // Create a test item that simulates a file
 9892        let item = cx.new(|cx| {
 9893            TestItem::new(cx)
 9894                .with_label("test.txt")
 9895                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9896        });
 9897
 9898        // Add item to workspace
 9899        workspace.update_in(cx, |workspace, window, cx| {
 9900            workspace.add_item(
 9901                pane.clone(),
 9902                Box::new(item.clone()),
 9903                None,
 9904                false,
 9905                false,
 9906                window,
 9907                cx,
 9908            );
 9909        });
 9910
 9911        // Verify the item is in the pane
 9912        pane.read_with(cx, |pane, _| {
 9913            assert_eq!(pane.items().count(), 1);
 9914        });
 9915
 9916        // Simulate file deletion by setting the item's deleted state
 9917        item.update(cx, |item, _| {
 9918            item.set_has_deleted_file(true);
 9919        });
 9920
 9921        // Emit UpdateTab event to trigger the close behavior
 9922        cx.run_until_parked();
 9923        item.update(cx, |_, cx| {
 9924            cx.emit(ItemEvent::UpdateTab);
 9925        });
 9926
 9927        // Allow the close operation to complete
 9928        cx.run_until_parked();
 9929
 9930        // Verify the item was automatically closed
 9931        pane.read_with(cx, |pane, _| {
 9932            assert_eq!(
 9933                pane.items().count(),
 9934                0,
 9935                "Item should be automatically closed when file is deleted"
 9936            );
 9937        });
 9938    }
 9939
 9940    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9941    /// open with a strikethrough when they are deleted from disk.
 9942    #[gpui::test]
 9943    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9944        init_test(cx);
 9945
 9946        // Ensure close_on_disk_deletion is disabled (default)
 9947        cx.update_global(|store: &mut SettingsStore, cx| {
 9948            store.update_user_settings(cx, |settings| {
 9949                settings.workspace.close_on_file_delete = Some(false);
 9950            });
 9951        });
 9952
 9953        let fs = FakeFs::new(cx.background_executor.clone());
 9954        let project = Project::test(fs, [], cx).await;
 9955        let (workspace, cx) =
 9956            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9957        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9958
 9959        // Create a test item that simulates a file
 9960        let item = cx.new(|cx| {
 9961            TestItem::new(cx)
 9962                .with_label("test.txt")
 9963                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9964        });
 9965
 9966        // Add item to workspace
 9967        workspace.update_in(cx, |workspace, window, cx| {
 9968            workspace.add_item(
 9969                pane.clone(),
 9970                Box::new(item.clone()),
 9971                None,
 9972                false,
 9973                false,
 9974                window,
 9975                cx,
 9976            );
 9977        });
 9978
 9979        // Verify the item is in the pane
 9980        pane.read_with(cx, |pane, _| {
 9981            assert_eq!(pane.items().count(), 1);
 9982        });
 9983
 9984        // Simulate file deletion
 9985        item.update(cx, |item, _| {
 9986            item.set_has_deleted_file(true);
 9987        });
 9988
 9989        // Emit UpdateTab event
 9990        cx.run_until_parked();
 9991        item.update(cx, |_, cx| {
 9992            cx.emit(ItemEvent::UpdateTab);
 9993        });
 9994
 9995        // Allow any potential close operation to complete
 9996        cx.run_until_parked();
 9997
 9998        // Verify the item remains open (with strikethrough)
 9999        pane.read_with(cx, |pane, _| {
10000            assert_eq!(
10001                pane.items().count(),
10002                1,
10003                "Item should remain open when close_on_disk_deletion is disabled"
10004            );
10005        });
10006
10007        // Verify the item shows as deleted
10008        item.read_with(cx, |item, _| {
10009            assert!(
10010                item.has_deleted_file,
10011                "Item should be marked as having deleted file"
10012            );
10013        });
10014    }
10015
10016    /// Tests that dirty files are not automatically closed when deleted from disk,
10017    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10018    /// unsaved changes without being prompted.
10019    #[gpui::test]
10020    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10021        init_test(cx);
10022
10023        // Enable the close_on_file_delete setting
10024        cx.update_global(|store: &mut SettingsStore, cx| {
10025            store.update_user_settings(cx, |settings| {
10026                settings.workspace.close_on_file_delete = Some(true);
10027            });
10028        });
10029
10030        let fs = FakeFs::new(cx.background_executor.clone());
10031        let project = Project::test(fs, [], cx).await;
10032        let (workspace, cx) =
10033            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10034        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10035
10036        // Create a dirty test item
10037        let item = cx.new(|cx| {
10038            TestItem::new(cx)
10039                .with_dirty(true)
10040                .with_label("test.txt")
10041                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10042        });
10043
10044        // Add item to workspace
10045        workspace.update_in(cx, |workspace, window, cx| {
10046            workspace.add_item(
10047                pane.clone(),
10048                Box::new(item.clone()),
10049                None,
10050                false,
10051                false,
10052                window,
10053                cx,
10054            );
10055        });
10056
10057        // Simulate file deletion
10058        item.update(cx, |item, _| {
10059            item.set_has_deleted_file(true);
10060        });
10061
10062        // Emit UpdateTab event to trigger the close behavior
10063        cx.run_until_parked();
10064        item.update(cx, |_, cx| {
10065            cx.emit(ItemEvent::UpdateTab);
10066        });
10067
10068        // Allow any potential close operation to complete
10069        cx.run_until_parked();
10070
10071        // Verify the item remains open (dirty files are not auto-closed)
10072        pane.read_with(cx, |pane, _| {
10073            assert_eq!(
10074                pane.items().count(),
10075                1,
10076                "Dirty items should not be automatically closed even when file is deleted"
10077            );
10078        });
10079
10080        // Verify the item is marked as deleted and still dirty
10081        item.read_with(cx, |item, _| {
10082            assert!(
10083                item.has_deleted_file,
10084                "Item should be marked as having deleted file"
10085            );
10086            assert!(item.is_dirty, "Item should still be dirty");
10087        });
10088    }
10089
10090    /// Tests that navigation history is cleaned up when files are auto-closed
10091    /// due to deletion from disk.
10092    #[gpui::test]
10093    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10094        init_test(cx);
10095
10096        // Enable the close_on_file_delete setting
10097        cx.update_global(|store: &mut SettingsStore, cx| {
10098            store.update_user_settings(cx, |settings| {
10099                settings.workspace.close_on_file_delete = Some(true);
10100            });
10101        });
10102
10103        let fs = FakeFs::new(cx.background_executor.clone());
10104        let project = Project::test(fs, [], cx).await;
10105        let (workspace, cx) =
10106            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10107        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10108
10109        // Create test items
10110        let item1 = cx.new(|cx| {
10111            TestItem::new(cx)
10112                .with_label("test1.txt")
10113                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10114        });
10115        let item1_id = item1.item_id();
10116
10117        let item2 = cx.new(|cx| {
10118            TestItem::new(cx)
10119                .with_label("test2.txt")
10120                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10121        });
10122
10123        // Add items to workspace
10124        workspace.update_in(cx, |workspace, window, cx| {
10125            workspace.add_item(
10126                pane.clone(),
10127                Box::new(item1.clone()),
10128                None,
10129                false,
10130                false,
10131                window,
10132                cx,
10133            );
10134            workspace.add_item(
10135                pane.clone(),
10136                Box::new(item2.clone()),
10137                None,
10138                false,
10139                false,
10140                window,
10141                cx,
10142            );
10143        });
10144
10145        // Activate item1 to ensure it gets navigation entries
10146        pane.update_in(cx, |pane, window, cx| {
10147            pane.activate_item(0, true, true, window, cx);
10148        });
10149
10150        // Switch to item2 and back to create navigation history
10151        pane.update_in(cx, |pane, window, cx| {
10152            pane.activate_item(1, true, true, window, cx);
10153        });
10154        cx.run_until_parked();
10155
10156        pane.update_in(cx, |pane, window, cx| {
10157            pane.activate_item(0, true, true, window, cx);
10158        });
10159        cx.run_until_parked();
10160
10161        // Simulate file deletion for item1
10162        item1.update(cx, |item, _| {
10163            item.set_has_deleted_file(true);
10164        });
10165
10166        // Emit UpdateTab event to trigger the close behavior
10167        item1.update(cx, |_, cx| {
10168            cx.emit(ItemEvent::UpdateTab);
10169        });
10170        cx.run_until_parked();
10171
10172        // Verify item1 was closed
10173        pane.read_with(cx, |pane, _| {
10174            assert_eq!(
10175                pane.items().count(),
10176                1,
10177                "Should have 1 item remaining after auto-close"
10178            );
10179        });
10180
10181        // Check navigation history after close
10182        let has_item = pane.read_with(cx, |pane, cx| {
10183            let mut has_item = false;
10184            pane.nav_history().for_each_entry(cx, |entry, _| {
10185                if entry.item.id() == item1_id {
10186                    has_item = true;
10187                }
10188            });
10189            has_item
10190        });
10191
10192        assert!(
10193            !has_item,
10194            "Navigation history should not contain closed item entries"
10195        );
10196    }
10197
10198    #[gpui::test]
10199    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10200        cx: &mut TestAppContext,
10201    ) {
10202        init_test(cx);
10203
10204        let fs = FakeFs::new(cx.background_executor.clone());
10205        let project = Project::test(fs, [], cx).await;
10206        let (workspace, cx) =
10207            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10208        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10209
10210        let dirty_regular_buffer = cx.new(|cx| {
10211            TestItem::new(cx)
10212                .with_dirty(true)
10213                .with_label("1.txt")
10214                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10215        });
10216        let dirty_regular_buffer_2 = cx.new(|cx| {
10217            TestItem::new(cx)
10218                .with_dirty(true)
10219                .with_label("2.txt")
10220                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10221        });
10222        let clear_regular_buffer = cx.new(|cx| {
10223            TestItem::new(cx)
10224                .with_label("3.txt")
10225                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10226        });
10227
10228        let dirty_multi_buffer = cx.new(|cx| {
10229            TestItem::new(cx)
10230                .with_dirty(true)
10231                .with_buffer_kind(ItemBufferKind::Multibuffer)
10232                .with_label("Fake Project Search")
10233                .with_project_items(&[
10234                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10235                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10236                    clear_regular_buffer.read(cx).project_items[0].clone(),
10237                ])
10238        });
10239        workspace.update_in(cx, |workspace, window, cx| {
10240            workspace.add_item(
10241                pane.clone(),
10242                Box::new(dirty_regular_buffer.clone()),
10243                None,
10244                false,
10245                false,
10246                window,
10247                cx,
10248            );
10249            workspace.add_item(
10250                pane.clone(),
10251                Box::new(dirty_regular_buffer_2.clone()),
10252                None,
10253                false,
10254                false,
10255                window,
10256                cx,
10257            );
10258            workspace.add_item(
10259                pane.clone(),
10260                Box::new(dirty_multi_buffer.clone()),
10261                None,
10262                false,
10263                false,
10264                window,
10265                cx,
10266            );
10267        });
10268
10269        pane.update_in(cx, |pane, window, cx| {
10270            pane.activate_item(2, true, true, window, cx);
10271            assert_eq!(
10272                pane.active_item().unwrap().item_id(),
10273                dirty_multi_buffer.item_id(),
10274                "Should select the multi buffer in the pane"
10275            );
10276        });
10277        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10278            pane.close_active_item(
10279                &CloseActiveItem {
10280                    save_intent: None,
10281                    close_pinned: false,
10282                },
10283                window,
10284                cx,
10285            )
10286        });
10287        cx.background_executor.run_until_parked();
10288        assert!(
10289            !cx.has_pending_prompt(),
10290            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10291        );
10292        close_multi_buffer_task
10293            .await
10294            .expect("Closing multi buffer failed");
10295        pane.update(cx, |pane, cx| {
10296            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10297            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10298            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10299            assert_eq!(
10300                pane.items()
10301                    .map(|item| item.item_id())
10302                    .sorted()
10303                    .collect::<Vec<_>>(),
10304                vec![
10305                    dirty_regular_buffer.item_id(),
10306                    dirty_regular_buffer_2.item_id(),
10307                ],
10308                "Should have no multi buffer left in the pane"
10309            );
10310            assert!(dirty_regular_buffer.read(cx).is_dirty);
10311            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10312        });
10313    }
10314
10315    #[gpui::test]
10316    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10317        init_test(cx);
10318        let fs = FakeFs::new(cx.executor());
10319        let project = Project::test(fs, [], cx).await;
10320        let (workspace, cx) =
10321            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10322
10323        // Add a new panel to the right dock, opening the dock and setting the
10324        // focus to the new panel.
10325        let panel = workspace.update_in(cx, |workspace, window, cx| {
10326            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10327            workspace.add_panel(panel.clone(), window, cx);
10328
10329            workspace
10330                .right_dock()
10331                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10332
10333            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10334
10335            panel
10336        });
10337
10338        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10339        // panel to the next valid position which, in this case, is the left
10340        // dock.
10341        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10342        workspace.update(cx, |workspace, cx| {
10343            assert!(workspace.left_dock().read(cx).is_open());
10344            assert_eq!(panel.read(cx).position, DockPosition::Left);
10345        });
10346
10347        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10348        // panel to the next valid position which, in this case, is the bottom
10349        // dock.
10350        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10351        workspace.update(cx, |workspace, cx| {
10352            assert!(workspace.bottom_dock().read(cx).is_open());
10353            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10354        });
10355
10356        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10357        // around moving the panel to its initial position, the right dock.
10358        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10359        workspace.update(cx, |workspace, cx| {
10360            assert!(workspace.right_dock().read(cx).is_open());
10361            assert_eq!(panel.read(cx).position, DockPosition::Right);
10362        });
10363
10364        // Remove focus from the panel, ensuring that, if the panel is not
10365        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10366        // the panel's position, so the panel is still in the right dock.
10367        workspace.update_in(cx, |workspace, window, cx| {
10368            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10369        });
10370
10371        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10372        workspace.update(cx, |workspace, cx| {
10373            assert!(workspace.right_dock().read(cx).is_open());
10374            assert_eq!(panel.read(cx).position, DockPosition::Right);
10375        });
10376    }
10377
10378    #[gpui::test]
10379    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10380        init_test(cx);
10381
10382        let fs = FakeFs::new(cx.executor());
10383        let project = Project::test(fs, [], cx).await;
10384        let (workspace, cx) =
10385            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10386
10387        let item_1 = cx.new(|cx| {
10388            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10389        });
10390        workspace.update_in(cx, |workspace, window, cx| {
10391            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10392            workspace.move_item_to_pane_in_direction(
10393                &MoveItemToPaneInDirection {
10394                    direction: SplitDirection::Right,
10395                    focus: true,
10396                    clone: false,
10397                },
10398                window,
10399                cx,
10400            );
10401            workspace.move_item_to_pane_at_index(
10402                &MoveItemToPane {
10403                    destination: 3,
10404                    focus: true,
10405                    clone: false,
10406                },
10407                window,
10408                cx,
10409            );
10410
10411            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10412            assert_eq!(
10413                pane_items_paths(&workspace.active_pane, cx),
10414                vec!["first.txt".to_string()],
10415                "Single item was not moved anywhere"
10416            );
10417        });
10418
10419        let item_2 = cx.new(|cx| {
10420            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10421        });
10422        workspace.update_in(cx, |workspace, window, cx| {
10423            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10424            assert_eq!(
10425                pane_items_paths(&workspace.panes[0], cx),
10426                vec!["first.txt".to_string(), "second.txt".to_string()],
10427            );
10428            workspace.move_item_to_pane_in_direction(
10429                &MoveItemToPaneInDirection {
10430                    direction: SplitDirection::Right,
10431                    focus: true,
10432                    clone: false,
10433                },
10434                window,
10435                cx,
10436            );
10437
10438            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10439            assert_eq!(
10440                pane_items_paths(&workspace.panes[0], cx),
10441                vec!["first.txt".to_string()],
10442                "After moving, one item should be left in the original pane"
10443            );
10444            assert_eq!(
10445                pane_items_paths(&workspace.panes[1], cx),
10446                vec!["second.txt".to_string()],
10447                "New item should have been moved to the new pane"
10448            );
10449        });
10450
10451        let item_3 = cx.new(|cx| {
10452            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10453        });
10454        workspace.update_in(cx, |workspace, window, cx| {
10455            let original_pane = workspace.panes[0].clone();
10456            workspace.set_active_pane(&original_pane, window, cx);
10457            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10458            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10459            assert_eq!(
10460                pane_items_paths(&workspace.active_pane, cx),
10461                vec!["first.txt".to_string(), "third.txt".to_string()],
10462                "New pane should be ready to move one item out"
10463            );
10464
10465            workspace.move_item_to_pane_at_index(
10466                &MoveItemToPane {
10467                    destination: 3,
10468                    focus: true,
10469                    clone: false,
10470                },
10471                window,
10472                cx,
10473            );
10474            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10475            assert_eq!(
10476                pane_items_paths(&workspace.active_pane, cx),
10477                vec!["first.txt".to_string()],
10478                "After moving, one item should be left in the original pane"
10479            );
10480            assert_eq!(
10481                pane_items_paths(&workspace.panes[1], cx),
10482                vec!["second.txt".to_string()],
10483                "Previously created pane should be unchanged"
10484            );
10485            assert_eq!(
10486                pane_items_paths(&workspace.panes[2], cx),
10487                vec!["third.txt".to_string()],
10488                "New item should have been moved to the new pane"
10489            );
10490        });
10491    }
10492
10493    #[gpui::test]
10494    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10495        init_test(cx);
10496
10497        let fs = FakeFs::new(cx.executor());
10498        let project = Project::test(fs, [], cx).await;
10499        let (workspace, cx) =
10500            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10501
10502        let item_1 = cx.new(|cx| {
10503            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10504        });
10505        workspace.update_in(cx, |workspace, window, cx| {
10506            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10507            workspace.move_item_to_pane_in_direction(
10508                &MoveItemToPaneInDirection {
10509                    direction: SplitDirection::Right,
10510                    focus: true,
10511                    clone: true,
10512                },
10513                window,
10514                cx,
10515            );
10516            workspace.move_item_to_pane_at_index(
10517                &MoveItemToPane {
10518                    destination: 3,
10519                    focus: true,
10520                    clone: true,
10521                },
10522                window,
10523                cx,
10524            );
10525
10526            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10527            for pane in workspace.panes() {
10528                assert_eq!(
10529                    pane_items_paths(pane, cx),
10530                    vec!["first.txt".to_string()],
10531                    "Single item exists in all panes"
10532                );
10533            }
10534        });
10535
10536        // verify that the active pane has been updated after waiting for the
10537        // pane focus event to fire and resolve
10538        workspace.read_with(cx, |workspace, _app| {
10539            assert_eq!(
10540                workspace.active_pane(),
10541                &workspace.panes[2],
10542                "The third pane should be the active one: {:?}",
10543                workspace.panes
10544            );
10545        })
10546    }
10547
10548    mod register_project_item_tests {
10549
10550        use super::*;
10551
10552        // View
10553        struct TestPngItemView {
10554            focus_handle: FocusHandle,
10555        }
10556        // Model
10557        struct TestPngItem {}
10558
10559        impl project::ProjectItem for TestPngItem {
10560            fn try_open(
10561                _project: &Entity<Project>,
10562                path: &ProjectPath,
10563                cx: &mut App,
10564            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10565                if path.path.extension().unwrap() == "png" {
10566                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10567                } else {
10568                    None
10569                }
10570            }
10571
10572            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10573                None
10574            }
10575
10576            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10577                None
10578            }
10579
10580            fn is_dirty(&self) -> bool {
10581                false
10582            }
10583        }
10584
10585        impl Item for TestPngItemView {
10586            type Event = ();
10587            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10588                "".into()
10589            }
10590        }
10591        impl EventEmitter<()> for TestPngItemView {}
10592        impl Focusable for TestPngItemView {
10593            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10594                self.focus_handle.clone()
10595            }
10596        }
10597
10598        impl Render for TestPngItemView {
10599            fn render(
10600                &mut self,
10601                _window: &mut Window,
10602                _cx: &mut Context<Self>,
10603            ) -> impl IntoElement {
10604                Empty
10605            }
10606        }
10607
10608        impl ProjectItem for TestPngItemView {
10609            type Item = TestPngItem;
10610
10611            fn for_project_item(
10612                _project: Entity<Project>,
10613                _pane: Option<&Pane>,
10614                _item: Entity<Self::Item>,
10615                _: &mut Window,
10616                cx: &mut Context<Self>,
10617            ) -> Self
10618            where
10619                Self: Sized,
10620            {
10621                Self {
10622                    focus_handle: cx.focus_handle(),
10623                }
10624            }
10625        }
10626
10627        // View
10628        struct TestIpynbItemView {
10629            focus_handle: FocusHandle,
10630        }
10631        // Model
10632        struct TestIpynbItem {}
10633
10634        impl project::ProjectItem for TestIpynbItem {
10635            fn try_open(
10636                _project: &Entity<Project>,
10637                path: &ProjectPath,
10638                cx: &mut App,
10639            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10640                if path.path.extension().unwrap() == "ipynb" {
10641                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10642                } else {
10643                    None
10644                }
10645            }
10646
10647            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10648                None
10649            }
10650
10651            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10652                None
10653            }
10654
10655            fn is_dirty(&self) -> bool {
10656                false
10657            }
10658        }
10659
10660        impl Item for TestIpynbItemView {
10661            type Event = ();
10662            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10663                "".into()
10664            }
10665        }
10666        impl EventEmitter<()> for TestIpynbItemView {}
10667        impl Focusable for TestIpynbItemView {
10668            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10669                self.focus_handle.clone()
10670            }
10671        }
10672
10673        impl Render for TestIpynbItemView {
10674            fn render(
10675                &mut self,
10676                _window: &mut Window,
10677                _cx: &mut Context<Self>,
10678            ) -> impl IntoElement {
10679                Empty
10680            }
10681        }
10682
10683        impl ProjectItem for TestIpynbItemView {
10684            type Item = TestIpynbItem;
10685
10686            fn for_project_item(
10687                _project: Entity<Project>,
10688                _pane: Option<&Pane>,
10689                _item: Entity<Self::Item>,
10690                _: &mut Window,
10691                cx: &mut Context<Self>,
10692            ) -> Self
10693            where
10694                Self: Sized,
10695            {
10696                Self {
10697                    focus_handle: cx.focus_handle(),
10698                }
10699            }
10700        }
10701
10702        struct TestAlternatePngItemView {
10703            focus_handle: FocusHandle,
10704        }
10705
10706        impl Item for TestAlternatePngItemView {
10707            type Event = ();
10708            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10709                "".into()
10710            }
10711        }
10712
10713        impl EventEmitter<()> for TestAlternatePngItemView {}
10714        impl Focusable for TestAlternatePngItemView {
10715            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10716                self.focus_handle.clone()
10717            }
10718        }
10719
10720        impl Render for TestAlternatePngItemView {
10721            fn render(
10722                &mut self,
10723                _window: &mut Window,
10724                _cx: &mut Context<Self>,
10725            ) -> impl IntoElement {
10726                Empty
10727            }
10728        }
10729
10730        impl ProjectItem for TestAlternatePngItemView {
10731            type Item = TestPngItem;
10732
10733            fn for_project_item(
10734                _project: Entity<Project>,
10735                _pane: Option<&Pane>,
10736                _item: Entity<Self::Item>,
10737                _: &mut Window,
10738                cx: &mut Context<Self>,
10739            ) -> Self
10740            where
10741                Self: Sized,
10742            {
10743                Self {
10744                    focus_handle: cx.focus_handle(),
10745                }
10746            }
10747        }
10748
10749        #[gpui::test]
10750        async fn test_register_project_item(cx: &mut TestAppContext) {
10751            init_test(cx);
10752
10753            cx.update(|cx| {
10754                register_project_item::<TestPngItemView>(cx);
10755                register_project_item::<TestIpynbItemView>(cx);
10756            });
10757
10758            let fs = FakeFs::new(cx.executor());
10759            fs.insert_tree(
10760                "/root1",
10761                json!({
10762                    "one.png": "BINARYDATAHERE",
10763                    "two.ipynb": "{ totally a notebook }",
10764                    "three.txt": "editing text, sure why not?"
10765                }),
10766            )
10767            .await;
10768
10769            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10770            let (workspace, cx) =
10771                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10772
10773            let worktree_id = project.update(cx, |project, cx| {
10774                project.worktrees(cx).next().unwrap().read(cx).id()
10775            });
10776
10777            let handle = workspace
10778                .update_in(cx, |workspace, window, cx| {
10779                    let project_path = (worktree_id, rel_path("one.png"));
10780                    workspace.open_path(project_path, None, true, window, cx)
10781                })
10782                .await
10783                .unwrap();
10784
10785            // Now we can check if the handle we got back errored or not
10786            assert_eq!(
10787                handle.to_any().entity_type(),
10788                TypeId::of::<TestPngItemView>()
10789            );
10790
10791            let handle = workspace
10792                .update_in(cx, |workspace, window, cx| {
10793                    let project_path = (worktree_id, rel_path("two.ipynb"));
10794                    workspace.open_path(project_path, None, true, window, cx)
10795                })
10796                .await
10797                .unwrap();
10798
10799            assert_eq!(
10800                handle.to_any().entity_type(),
10801                TypeId::of::<TestIpynbItemView>()
10802            );
10803
10804            let handle = workspace
10805                .update_in(cx, |workspace, window, cx| {
10806                    let project_path = (worktree_id, rel_path("three.txt"));
10807                    workspace.open_path(project_path, None, true, window, cx)
10808                })
10809                .await;
10810            assert!(handle.is_err());
10811        }
10812
10813        #[gpui::test]
10814        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10815            init_test(cx);
10816
10817            cx.update(|cx| {
10818                register_project_item::<TestPngItemView>(cx);
10819                register_project_item::<TestAlternatePngItemView>(cx);
10820            });
10821
10822            let fs = FakeFs::new(cx.executor());
10823            fs.insert_tree(
10824                "/root1",
10825                json!({
10826                    "one.png": "BINARYDATAHERE",
10827                    "two.ipynb": "{ totally a notebook }",
10828                    "three.txt": "editing text, sure why not?"
10829                }),
10830            )
10831            .await;
10832            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10833            let (workspace, cx) =
10834                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10835            let worktree_id = project.update(cx, |project, cx| {
10836                project.worktrees(cx).next().unwrap().read(cx).id()
10837            });
10838
10839            let handle = workspace
10840                .update_in(cx, |workspace, window, cx| {
10841                    let project_path = (worktree_id, rel_path("one.png"));
10842                    workspace.open_path(project_path, None, true, window, cx)
10843                })
10844                .await
10845                .unwrap();
10846
10847            // This _must_ be the second item registered
10848            assert_eq!(
10849                handle.to_any().entity_type(),
10850                TypeId::of::<TestAlternatePngItemView>()
10851            );
10852
10853            let handle = workspace
10854                .update_in(cx, |workspace, window, cx| {
10855                    let project_path = (worktree_id, rel_path("three.txt"));
10856                    workspace.open_path(project_path, None, true, window, cx)
10857                })
10858                .await;
10859            assert!(handle.is_err());
10860        }
10861    }
10862
10863    #[gpui::test]
10864    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
10865        init_test(cx);
10866
10867        let fs = FakeFs::new(cx.executor());
10868        let project = Project::test(fs, [], cx).await;
10869        let (workspace, _cx) =
10870            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10871
10872        // Test with status bar shown (default)
10873        workspace.read_with(cx, |workspace, cx| {
10874            let visible = workspace.status_bar_visible(cx);
10875            assert!(visible, "Status bar should be visible by default");
10876        });
10877
10878        // Test with status bar hidden
10879        cx.update_global(|store: &mut SettingsStore, cx| {
10880            store.update_user_settings(cx, |settings| {
10881                settings.status_bar.get_or_insert_default().show = Some(false);
10882            });
10883        });
10884
10885        workspace.read_with(cx, |workspace, cx| {
10886            let visible = workspace.status_bar_visible(cx);
10887            assert!(!visible, "Status bar should be hidden when show is false");
10888        });
10889
10890        // Test with status bar shown explicitly
10891        cx.update_global(|store: &mut SettingsStore, cx| {
10892            store.update_user_settings(cx, |settings| {
10893                settings.status_bar.get_or_insert_default().show = Some(true);
10894            });
10895        });
10896
10897        workspace.read_with(cx, |workspace, cx| {
10898            let visible = workspace.status_bar_visible(cx);
10899            assert!(visible, "Status bar should be visible when show is true");
10900        });
10901    }
10902
10903    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10904        pane.read(cx)
10905            .items()
10906            .flat_map(|item| {
10907                item.project_paths(cx)
10908                    .into_iter()
10909                    .map(|path| path.path.display(PathStyle::local()).into_owned())
10910            })
10911            .collect()
10912    }
10913
10914    pub fn init_test(cx: &mut TestAppContext) {
10915        cx.update(|cx| {
10916            let settings_store = SettingsStore::test(cx);
10917            cx.set_global(settings_store);
10918            theme::init(theme::LoadThemes::JustBase, cx);
10919            language::init(cx);
10920            crate::init_settings(cx);
10921            Project::init_settings(cx);
10922        });
10923    }
10924
10925    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10926        let item = TestProjectItem::new(id, path, cx);
10927        item.update(cx, |item, _| {
10928            item.is_dirty = true;
10929        });
10930        item
10931    }
10932}