workspace.rs

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